Stats

 Latest version : 2.5.1

 Last updated on 2019-06-20T18:14:21.729Z

 Keywords : util, modules, cross-browser

 Downloads :

  • 214 in Last Month

 Links :

 Examples

¯\_(ツ)_/¯
No examples found for this package

 Readme

AdLibs

Build Status Coverage Status Code Climate Average time to resolve an issue Percentage of issues still open Dependency Status

| __ | The gist of it... | |:---|:---| | adlibs | A collection of cross-browser methods for use with front-end development. adlibs is a tool that supports various browser and OS combinations dating back to IE9. It uses feature detection to determine the user's environment and outputs details pertaining to that OS and browser. adlibs also allows developers to safely execute front end methods such as domReady and XMLHttpRequests across all browsers. |

Installation

npm install adlibs

Usage

Each function is exported as a single commonjs module, allowing only the needed modules to be bundled into a project to keep minified bundles as small as possible.

In Node.js:

// Load the full adlibs build.
var adlibs = require('adlibs');

// Load a single module for smaller builds with webpack.
var domReady = require('adlibs/lib/dom/domReady');
var browser = require('adlibs/lib/detect/browser');

Detection Modules

There are several modules that use feature detection to determine the user's environment. In order to populate the resulting objects, the detect function must be executed.

For example, in order to populate the browser object:

var browser = require('adlibs/lib/detect/browser').detect();

// outputs the name of the os
console.log(browser.os.name)

API Reference

Modules

canHas
comparableBits

This is due to Javascript using double-precision floating-point format numbers. If the number of bits in the bitmask is found to exceed the max supported, this module throws an error.

createSpysinon.spy

Helper method to create Sinon.JS spies directly on the value of module.exports for a required module. To spy on a method you need access to the object it is attached to, which is problematic when the function is directly returned from a "require" call. By accessing the require.cache we can get handle to the module's exports and inject the spy.

Browser

Browser Detection - Gets Data Pertaining to User's Browser and OS

Capabilities

Determines browser's capabilities (e.g. CORS support, sandboxable, video support, etc.)

Environment

Environment Detection - Gets Data Pertaining to User's Environment

embedHtml

Safely handles embedding of arbitrary HTML strings into the DOM (including embedding scripts that call document.write when the document has already been closed.)

Mraid

Mraid Detection

Safeframe

Safeframe Detection

addEventListenerfunction

Add an event listener to the element, which will execute the given callback.

appendHtml [deprecated]Array

Appends all elements in the html string to the parent element. Correctly handles scripts with src attributes and inline javascript and ensures that the script will execute. NOTE: Only Element nodes in the html string will be appended. All other node types will be ignored (i.e. Text, Comment).

domReady

Executes the provided callback when the DOM is ready. Allows code to act on the DOM before the window "load" event fires.

getExecutingScript
triggerEvent

Creates a new DOM Event and triggers it on the provided element.

evaluatorObject

Runs eval against the value passed to it. This function exists because eval prevents Uglify from minifying correctly. Encapsulating eval in its own module prevents the above issue. Variables and properties are one letter vars because Uglify won't function for this module. For more info on eval visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

jsonpObject

Perform a cross domain request via JSONP. Provides the same interface as xhr.js. The request is made by appending a 'callback' parameter to the request url, and it is expected that the server will respond with the content wrapped in a function call, using the provided value of the callback parameter. If callbackFn isn't defined, a unique name will be generated.

loadScript

Dynamically loads scripts in parallel, and executes a single callback after all scripts have loaded.

measurePerformance
parseConfigObject

Parses a json config from the provided Element. The defaults is expected to be a JSON string in the attribute value.

perfMarker

A module to mark the timestamps for script performance

reportData
formatString

Constructs a URL from its parsed components. 1) Host takes precedence over hostname and port. 2) Query takes precedence over search.

parseObject

Deconstructs a URL into its components. It also parses the search component (the query string) into decoded key/value pairs on a query object.

xhr

Cross browser wrapper for XMLHttpRequest. If you need Cookies and HTTP Auth data to be included in the request, you must set withCredentials to true in the options.

canHas

canHas.can(obj, propertyName) ⇒ Boolean

Can this object use this property?

Kind: static method of [canHas](#module_canHas)

| Param | | --- | | obj | | propertyName |

Example

var can = require('adlibs/lib/canHas').can;

canHas.has(globalObjectName, [scope]) ⇒ \*

Does this window have this object in it?

Kind: static method of [canHas](#module_canHas)

| Param | Description | | --- | --- | | globalObjectName | | | [scope] | Alternatively, you can call "run" with a more sane method signature. |

Example

var has = require('adlibs/lib/canHas').has;

canHas.own(obj, propertyName) ⇒ Boolean

Check to see if this object owns the method as opposed to just inheriting it from another object.

Kind: static method of [canHas](#module_canHas)

| Param | | --- | | obj | | propertyName |

canHas.run(obj, [methodName]) ⇒ function

Return a runnable method by default.

Kind: static method of [canHas](#module_canHas)

| Param | Description | | --- | --- | | obj | Scope to use, or method to run when not providing a method as the second param. | | [methodName] | The method to check for. |

canHas.forIn(obj, callback)

For each in, shorthanded because manually writing hasOwnProperty each and every time is not a good use of time.

Kind: static method of [canHas](#module_canHas)

| Param | | --- | | obj | | callback |

canHas.keys(obj) ⇒ \*

A substitute for Object.keys for when browsers don't attempt to convert non-objects to arrays

Kind: static method of [canHas](#module_canHas)

| Param | | --- | | obj |

comparableBits

This is due to Javascript using double-precision floating-point format numbers. If the number of bits in the bitmask is found to exceed the max supported, this module throws an error.

comparableBits.factory ⇒ ComparableBits

Create a new instance of the ComparableBits module.

Kind: static property of [comparableBits](#module_comparableBits)
Example

var bits = require('adlibs/lib/comparableBits').factory();

var someAction = bits.make(0x1 | 0x2, 'flag1,mode1or2')
bits.compare(someAction, 0x1, callback) // -> executes callback

comparableBits.provider ⇒ ComparableBits

Tie into an existing instance of the ComparableBits module.

Kind: static property of [comparableBits](#module_comparableBits)

| Param | | --- | | packageName |

comparableBits.make(bit, [data]) ⇒ Action

Creates the action object with it's attributed bitmask flag

Kind: static method of [comparableBits](#module_comparableBits)
Returns: Action - Returns the created Action object

| Param | Type | Description | | --- | --- | --- | | bit | Number | The actions's unique bitmask | | [data] | String | The action's label |

Example

var make = require('adlibs/lib/comparableBits').make;

comparableBits.compare(action, bitSig, [callback]) ⇒ Boolean

Encapsulates a bitmask service which takes a bitmask and compares it to the attributed action's flag

Kind: static method of [comparableBits](#module_comparableBits)
Returns: Boolean - Returns true if the action's flags do match either of the provided bitmasks

| Param | Type | Description | | --- | --- | --- | | action | Action | The action object to compare to the provided bitmasks | | bitSig | Number | Should have a unique bit signature for bit logic | | [callback] | \* | The action's pertaining data |

Example

var compare = require('adlibs/lib/comparableBits').compare;

createSpy ⇒ sinon.spy

Helper method to create Sinon.JS spies directly on the value of module.exports for a required module. To spy on a method you need access to the object it is attached to, which is problematic when the function is directly returned from a "require" call. By accessing the require.cache we can get handle to the module's exports and inject the spy.

| Param | Type | Description | | --- | --- | --- | | loadedModule | | | | mockType | String | Defaults to 'spy'; can also be 'stub'. |

Example
incrementCounter.js:

module.exports = function() { ... async call ...  };

my-test.js

var incrementCounter = require('./incrementCounter'),
createSpy = require('cse-common/lib/createSpy');

var spy = createSpy(incrementCounter);

// test code
assert(spy.callCount, 4);
spy.restore();

Browser

Browser Detection - Gets Data Pertaining to User's Browser and OS

Example

var browser = require("adlibs/lib/detect/browser")

browser.mathMLSupport(d) ⇒ Boolean

Check for MathML support in browsers to help detect certain browser version numbers where this is the only difference.

Kind: static method of [Browser](#module_Browser)
Returns: Boolean - returns true if browser has mathml support

| Param | Type | | --- | --- | | d | Document |

browser.isMobile([win]) ⇒ Boolean

Performs a simple test to see if we're on mobile or not.

Kind: static method of [Browser](#module_Browser)
Returns: Boolean - returns true if mobile

| Param | Type | | --- | --- | | [win] | Window |

browser.getVersion(uaVersion, minVersion, [maxVersion]) ⇒ Number

Uses the min and max versions of a browser to determine its version.

Kind: static method of [Browser](#module_Browser)
Returns: Number - returns version number

| Param | Type | | --- | --- | | uaVersion | Number | | minVersion | Number | | [maxVersion] | Number |

browser.looksLike(regex, ua) ⇒ \* | Boolean

Searches for a match between the regex and specified string.

Kind: static method of [Browser](#module_Browser)
Returns: \* | Boolean - returns true if match found

| Param | Type | | --- | --- | | regex | RegExp | | ua | String |

browser.parseIntIfMatch(ua, regex, [radix]) ⇒ Number

Parses the result of the RegExp match if it exists. Gracefully falls back to the default version if not.

Kind: static method of [Browser](#module_Browser)
Returns: Number - returns the regex match or default version

| Param | Type | | --- | --- | | ua | String | | regex | RegExp | | [radix] | Number |

browser.parseFloatIfMatch(ua, regex) ⇒

Parses the floating point value of the RegExp match if found. Gracefully falls back to the default if not.

Kind: static method of [Browser](#module_Browser)
Returns: returns the regex match or the default version

| Param | Type | | --- | --- | | ua | String | | regex | RegExp |

browser.getAndroidVersion(win, uaVersion) ⇒ Number

Determines the version of Android being used.

Kind: static method of [Browser](#module_Browser)
Returns: Number - returns the Android version

| Param | Type | | --- | --- | | win | Window | | uaVersion | Number |

browser.getChromiumVersion(win, uaVersion) ⇒ Number

Determines the version of Chrome being used.

Kind: static method of [Browser](#module_Browser)
Returns: Number - returns the Chrome version

| Param | Type | | --- | --- | | win | Window | | uaVersion | Number |

browser.getSafariVersion(win, uaVersion) ⇒ Number

Returns the version of the Safari browser.

Kind: static method of [Browser](#module_Browser)
Returns: Number - returns the version of Safari

| Param | Type | | --- | --- | | win | Window | | uaVersion | Number |

browser.getKindleVersion(win, uaVersion) ⇒ Number

Creates a Browser instance with its attributed Kindle values.

Kind: static method of [Browser](#module_Browser)

| Param | Type | | --- | --- | | win | Window | | uaVersion | Number |

browser.getOtherOS(win, ua) ⇒ Browser

Creates a Browser instance with its attributed OS and device type values.

Kind: static method of [Browser](#module_Browser)
Returns: Browser - returns the browser instance

| Param | Type | | --- | --- | | win | Window | | ua | String |

browser.getAppleOS(win, ua) ⇒ Browser

Creates a Browser instance with its attributed Apple values.

Kind: static method of [Browser](#module_Browser)
Returns: Browser - returns the Browser instance

| Param | Type | | --- | --- | | win | Window | | ua | String |

browser.getMicrosoftOS(win, ua) ⇒ Browser

Creates a Browser instance with its attributed Windows values.

Kind: static method of [Browser](#module_Browser)
Returns: Browser - returns the Browser instance

| Param | Type | | --- | --- | | win | Window | | ua | String |

browser.getAndroidOS(win, ua) ⇒ Browser

Creates a Browser instance with its attributed Android values.

Kind: static method of [Browser](#module_Browser)
Returns: Browser - returns the Browser instance

| Param | Type | | --- | --- | | win | Window | | ua | String |

browser.getKindleOS(win, ua) ⇒ Browser

Returns the Kindle's OS.

Kind: static method of [Browser](#module_Browser)
Returns: Browser - returns the Browser instance

| Param | Type | | --- | --- | | win | Window | | ua | String |

browser.getOsFromUa(win, ua) ⇒ Browser

Reads the user agent string to determine OS.

Kind: static method of [Browser](#module_Browser)
Returns: Browser - returns the Browser instance

| Param | Type | | --- | --- | | win | Window | | ua | String |

browser.detect([win], [userAgent]) ⇒ Browser

Returns an object containing browser details (e.g. name, os, version, etc.).

Kind: static method of [Browser](#module_Browser)
Returns: Browser - returns the Browser instance

| Param | Type | | --- | --- | | [win] | Window | | [userAgent] | String |

Example

var os = browser.detect().os.name;

console.log(os); // outputs OS name (e.g. Windows, Mac, Android, etc.)

browser.read(key) ⇒ \*

Retrieve any results in the map by name because they're returned in an array without names.

Kind: static method of [Browser](#module_Browser)

| Param | Type | | --- | --- | | key | String |

browser~save(result) ⇒ Number

Saves a property to the results array and returns its index.

Kind: inner method of [Browser](#module_Browser)

| Param | Type | | --- | --- | | result | \* |

Capabilities

Determines browser's capabilities (e.g. CORS support, sandboxable, video support, etc.)

Example

var capabilities = require("adlibs/lib/detect/capabilities");

capabilities.detect() ⇒ Object

Detects browser's capabilities and returns an object.

Kind: static method of [Capabilities](#module_Capabilities)
Example

// Outputs whether the browser supports h264 video ( 1 if yes, else 0)
var h264 = capabilities.detect().h264;

Environment

Environment Detection - Gets Data Pertaining to User's Environment

Example

var environment = require("adlibs/lib/detect/environment");

embedHtml

If the doc readyState is complete or interactive, use custom methods to safely write 'htmlString' to the page; otherwise, use native document.write

| Param | Type | | --- | --- | | htmlString | String | | [callback] | function |

Example

var embedHtml = require('adlibs/lib/dom/embedHtml'),
  htmlString = '<span>Hello World</span>',
  callbackFunc = function(container) {
    console.log(container.innerHTML);
  };

embedHtml(htmlString, callbackFunc);

environment.detect() ⇒ Object

Detect environmental variables and return them wrapped within an object.

Kind: static method of [Environment](#module_Environment)
Returns: Object - returns the environment object
Example

var flash = environment.detect().flash;

console.log(flash) // outputs the version of Flash

environment.getFlashVersion() ⇒ Number

Kind: static method of [Environment](#module_Environment)

environment.getFrameDepth() ⇒ String

Kind: static method of [Environment](#module_Environment)

environment.getAvailableScreenSize() ⇒ Object

Kind: static method of [Environment](#module_Environment)

environment.getScreenSize() ⇒ Object

Kind: static method of [Environment](#module_Environment)

environment.getAdDocSize() ⇒ Object

Kind: static method of [Environment](#module_Environment)

Mraid

Mraid Detection

Example

var mraid = require("adlibs/lib/detect/mraid");

console.log(mraid.getVersion()) // outputs mraid version;

mraid.ready(cb, [If])

Executes cb when mraid is ready.

Kind: static method of [Mraid](#module_Mraid)

| Param | Type | Description | | --- | --- | --- | | cb | function | | | [If] | Window | not given, uses the current window. |

mraid.getVersion([If]) ⇒ String

Gets mraid version.

Kind: static method of [Mraid](#module_Mraid)

| Param | Type | Description | | --- | --- | --- | | [If] | Window | not given, uses the current window. |

Safeframe

Safeframe Detection

Example

var safeframe = require("adlibs/lib/detect/safeframe");

Safeframe.getVersion([win]) ⇒ String

Get version of safeframe.

Kind: static method of [Safeframe](#module_Safeframe)

| Param | Type | | --- | --- | | [win] | Window |

Safeframe.getSpecVersion([win]) ⇒ String

Gets specVersion of safeframe.

Kind: static method of [Safeframe](#module_Safeframe)

| Param | Type | | --- | --- | | [win] | Window |

Safeframe.getInfo([win]) ⇒ Array

Gets info of safeframe.

Kind: static method of [Safeframe](#module_Safeframe)

| Param | Type | | --- | --- | | [win] | Window |

Safeframe.getConf([win]) ⇒ Array

Gets config of safeframe host.

Kind: static method of [Safeframe](#module_Safeframe)

| Param | Type | | --- | --- | | [win] | Window |

Safeframe.getSupport([win]) ⇒ Array

Returns array of supported fields for sf.ext.

Kind: static method of [Safeframe](#module_Safeframe)

| Param | Type | | --- | --- | | [win] | Window |

Safeframe.getInView([win]) ⇒ Number

Gets inview percentage of safeframe.

Kind: static method of [Safeframe](#module_Safeframe)

| Param | Type | | --- | --- | | [win] | Window |

Safeframe.getWinFocus([win]) ⇒ Number

Returns if safeframe window has focus.

Kind: static method of [Safeframe](#module_Safeframe)

| Param | Type | | --- | --- | | [win] | Window |

Safeframe.getMetrics([win]) ⇒ Array

Returns safeframe metrics.

Kind: static method of [Safeframe](#module_Safeframe)

| Param | Type | | --- | --- | | [win] | Window |

addEventListener ⇒ function

Add an event listener to the element, which will execute the given callback.

Returns: function - returns a function that, when executed, will remove the event listener from the element

| Param | Type | | --- | --- | | element | Element | | eventName | String | | callback | function |

Example

var addEventListener = require('adlibs/lib/dom/addEventListener');

addEventListener(el, 'onLoad', cb);

appendHtml ⇒ Array

Appends all elements in the html string to the parent element. Correctly handles scripts with src attributes and inline javascript and ensures that the script will execute. NOTE: Only Element nodes in the html string will be appended. All other node types will be ignored (i.e. Text, Comment).

Returns: Array - returns a list of any exceptions that occurred

| Param | Type | | --- | --- | | parentEl | Element | | html | String |

Example

var appendHtml = require('adlibs/lib/dom/appendHtml');

appendHtml(parentElement, htmlMarkup);

domReady

Executes the provided callback when the DOM is ready. Allows code to act on the DOM before the window "load" event fires.

| Param | Type | Description | | --- | --- | --- | | callback | function | | | [targetWindow] | Window | You can provide your own window reference for cases where you'd have an iframe. | | [isInteractiveOk] | Boolean | Interactive mode can be checked for faster responses. |

Example

var domReady = require('adlibs/lib/dom/domReady');

// executes the cb on dom ready
domReady(cb, window);

getExecutingScript

getExecutingScript~getExecutingScript([validatorFunc], [testScript]) ⇒ HTMLScriptElement | null

Returns the script element that loaded the currently executing javascript code.

The validatorFunc function takes a script Element as a single argument, and should return a boolean value. Allows more specific filtering in the case of multiple scripts on the page where document.currentScript is not supported.

When the executing script has been located, it will be marked with an attribute key/value pair represented at getExecutingScript.LOADATTR and getExecutingScript.LOADSTARTED.

Kind: inner method of [getExecutingScript](#module_getExecutingScript)

| Param | Type | Description | | --- | --- | --- | | [validatorFunc] | function | | | [testScript] | HTMLScriptElement | Used for IoC/testing. |

triggerEvent

Creates a new DOM Event and triggers it on the provided element.

| Param | Type | | --- | --- | | element | Element | | eventName | String |

evaluator ⇒ Object

Runs eval against the value passed to it. This function exists because eval prevents Uglify from minifying correctly. Encapsulating eval in its own module prevents the above issue. Variables and properties are one letter vars because Uglify won't function for this module. That's right - we have one letter vars in our source code. Ain't eval grand? For more info on eval visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

| Param | Type | | --- | --- | | v | String |

jsonp ⇒ Object

Perform a cross domain request via JSONP. Provides the same interface as xhr.js. The request is made by appending a 'callback' parameter to the request url, and it is expected that the server will respond with the content wrapped in a function call, using the provided value of the callback parameter. If callbackFn isn't defined, a unique name will be generated.

Returns: Object - returns object with send function

| Param | Type | Description | | --- | --- | --- | | options | Object | | | callback | function | Executed on response with the signature (status: Number, body: String). |

Example

// for call -> http://example.com/?callback=CB_1433519761916
// the following gets executed
CB_1433519761916('response from server');

loadScript

Dynamically loads scripts in parallel, and executes a single callback after all scripts have loaded.

| Param | Type | Description | | --- | --- | --- | | urls | String | Array | A single url, or a list of urls of scripts to load. | | onLoaded | function | Callback is executed when all scripts have finished loading. | | onError | function | Callback is executed if one or more scripts fail to load, and passed a single argument: the list of script urls that failed to load. | | [requestTimeout] | Number | When supplied, this will explicitly timeout the script request and report back to onError, or, if onError is not supplied, to onLoaded. IMPORTANT: This does not cancel the script load, just reports that it has exceeded the timeout duration. |

measurePerformance

measurePerformance.factory ⇒ MeasurePerformance

Create a new instance of the performance module.

Kind: static property of [measurePerformance](#module_measurePerformance)
Example

var perf = require('adlibs/lib/measurePerformance').factory();

console.log(perf.now() - perf.startTime); // outputs duration since script start
console.log(perf.report()); // outputs report based on performance events such as domLoading, navigationStart, etc.

measurePerformance.provider ⇒ MeasurePerformance

Tie into an existing instance of the performance module.

Kind: static property of [measurePerformance](#module_measurePerformance)

| Param | | --- | | packageName |

parseConfig ⇒ Object

Parses a json config from the provided Element. The defaults is expected to be a JSON string in the attribute value.

Returns: Object - returns the parsed json config

| Param | Type | Description | | --- | --- | --- | | el | Element | The HTML Element that contains the config defaults. | | attrName | String | | | [defaults] | Object | |

Example

var parseConfig = require('adlibs/lib/parseConfig');

console.log(parseConfig(htmlElement, attributeName, defaultVals)) // outputs the parsed object from the element

perfMarker

A module to mark the timestamps for script performance

perfMarker.factory ⇒ PerfMarker

Creates a new instance of PerfMarker.

Kind: static property of [perfMarker](#module_perfMarker)

perfMarker.provider ⇒ PerfMarker

Ties into an existing instance of PerfMarker.

Kind: static property of [perfMarker](#module_perfMarker)

| Param | Type | Description | | --- | --- | --- | | [pkgName] | String | The name of the instance. |

reportData

reportData.factory ⇒ ReportData

Create a new instance of the reportData module.

Kind: static property of [reportData](#module_reportData)

| Param | Type | Description | | --- | --- | --- | | [baseURL] | String | Base url for reporting pixel info. | | [measurePerformanceInstance] | MeasurePerformance | Performance instance to provide measurement timestamps. |

reportData.provider ⇒ ReportData

Tie into an existing instance of the reportData module.

Kind: static property of [reportData](#module_reportData)

| Param | | --- | | packageName |

format ⇒ String

Constructs a URL from its parsed components. 1) Host takes precedence over hostname and port. 2) Query takes precedence over search.

| Param | Type | Description | | --- | --- | --- | | components | Object | The url components, as generated by url/parse.js. |

parse ⇒ Object

Deconstructs a URL into its components. It also parses the search component (the query string) into decoded key/value pairs on a query object.

| Param | Type | | --- | --- | | url | String |

Example

var parseUrl = require('adlibs/lib/url/parse');

var queryObj = parseUrl('http://example.com/query?cb=1234&userid=9999');

xhr

Cross browser wrapper for XMLHttpRequest. If you need Cookies and HTTP Auth data to be included in the request, you must set withCredentials to true in the options.

Example

var xhr = require('adlibs/lib/xhr');

xhr.supportsCORS() ⇒ Boolean

Determines if CORS is supported.

Kind: static method of [xhr](#module_xhr)
Returns: Boolean - returns whether CORS is supported

xhr~xhr(options, callback) ⇒ Object

Kind: inner method of [xhr](#module_xhr)

| Param | Type | Description | | --- | --- | --- | | options | Object | | | callback | function | Executed on response with the signature (status: Number, body: String). |

Example

// performs a GET request
var resp = xhr({url: 'www.example.com'}).send();

adlibs Developers


 Comments