2.5.2 • Published 2 years ago

adlibs v2.5.2

Weekly downloads
5
License
Apache-2.0
Repository
github
Last release
2 years ago

AdLibs

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

____The gist of it...
adlibsA 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

Functions

canHas

canHas.can(obj, propertyName) ⇒ Boolean

Can this object use this property?

Kind: static method of 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

ParamDescription
globalObjectName
scopeAlternatively, 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

Param
obj
propertyName

canHas.run(obj, methodName) ⇒ function

Return a runnable method by default.

Kind: static method of canHas

ParamDescription
objScope to use, or method to run when not providing a method as the second param.
methodNameThe 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

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

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
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

Param
packageName

comparableBits.make(bit, data) ⇒ Action

Creates the action object with it's attributed bitmask flag

Kind: static method of comparableBits
Returns: Action - Returns the created Action object

ParamTypeDescription
bitNumberThe actions's unique bitmask
dataStringThe 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
Returns: Boolean - Returns true if the action's flags do match either of the provided bitmasks

ParamTypeDescription
actionActionThe action object to compare to the provided bitmasks
bitSigNumberShould 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.

ParamTypeDescription
loadedModule
mockTypeStringDefaults 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
Returns: Boolean - returns true if browser has mathml support

ParamType
dDocument

browser.isMobile(win) ⇒ Boolean

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

Kind: static method of Browser
Returns: Boolean - returns true if mobile

ParamType
winWindow

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

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

Kind: static method of Browser
Returns: Number - returns version number

ParamType
uaVersionNumber
minVersionNumber
maxVersionNumber

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

Searches for a match between the regex and specified string.

Kind: static method of Browser
Returns: * | Boolean - returns true if match found

ParamType
regexRegExp
uaString

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
Returns: Number - returns the regex match or default version

ParamType
uaString
regexRegExp
radixNumber

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
Returns: returns the regex match or the default version

ParamType
uaString
regexRegExp

browser.getAndroidVersion(win, uaVersion) ⇒ Number

Determines the version of Android being used.

Kind: static method of Browser
Returns: Number - returns the Android version

ParamType
winWindow
uaVersionNumber

browser.getChromiumVersion(win, uaVersion) ⇒ Number

Determines the version of Chrome being used.

Kind: static method of Browser
Returns: Number - returns the Chrome version

ParamType
winWindow
uaVersionNumber

browser.getSafariVersion(win, uaVersion) ⇒ Number

Returns the version of the Safari browser.

Kind: static method of Browser
Returns: Number - returns the version of Safari

ParamType
winWindow
uaVersionNumber

browser.getKindleVersion(win, uaVersion) ⇒ Number

Creates a Browser instance with its attributed Kindle values.

Kind: static method of Browser

ParamType
winWindow
uaVersionNumber

browser.getOtherOS(win, ua) ⇒ Browser

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

Kind: static method of Browser
Returns: Browser - returns the browser instance

ParamType
winWindow
uaString

browser.getAppleOS(win, ua) ⇒ Browser

Creates a Browser instance with its attributed Apple values.

Kind: static method of Browser
Returns: Browser - returns the Browser instance

ParamType
winWindow
uaString

browser.getMicrosoftOS(win, ua) ⇒ Browser

Creates a Browser instance with its attributed Windows values.

Kind: static method of Browser
Returns: Browser - returns the Browser instance

ParamType
winWindow
uaString

browser.getAndroidOS(win, ua) ⇒ Browser

Creates a Browser instance with its attributed Android values.

Kind: static method of Browser
Returns: Browser - returns the Browser instance

ParamType
winWindow
uaString

browser.getKindleOS(win, ua) ⇒ Browser

Returns the Kindle's OS.

Kind: static method of Browser
Returns: Browser - returns the Browser instance

ParamType
winWindow
uaString

browser.getOsFromUa(win, ua) ⇒ Browser

Reads the user agent string to determine OS.

Kind: static method of Browser
Returns: Browser - returns the Browser instance

ParamType
winWindow
uaString

browser.detect(win, userAgent) ⇒ Browser

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

Kind: static method of Browser
Returns: Browser - returns the Browser instance

ParamType
winWindow
userAgentString

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

ParamType
keyString

Browser~save(result) ⇒ Number

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

Kind: inner method of Browser

ParamType
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
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");

environment.detect() ⇒ Object

Detect environmental variables and return them wrapped within an object.

Kind: static method of 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

environment.getFrameDepth() ⇒ String

Kind: static method of Environment

environment.getAvailableScreenSize() ⇒ Object

Kind: static method of Environment

environment.getScreenSize() ⇒ Object

Kind: static method of Environment

environment.getAdDocSize() ⇒ Object

Kind: static method of 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

ParamTypeDescription
cbfunction
IfWindownot given, uses the current window.

mraid.getVersion(If) ⇒ String

Gets mraid version.

Kind: static method of Mraid

ParamTypeDescription
IfWindownot given, uses the current window.

mraid.diagnostic(win) ⇒ Object

Kind: static method of Mraid

ParamTypeDescription
winObjectWindow Object

Safeframe

Safeframe Detection

Example

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

Safeframe.getVersion(win) ⇒ String

Get version of safeframe.

Kind: static method of Safeframe

ParamType
winWindow

Safeframe.getSpecVersion(win) ⇒ String

Gets specVersion of safeframe.

Kind: static method of Safeframe

ParamType
winWindow

Safeframe.getInfo(win) ⇒ Array

Gets info of safeframe.

Kind: static method of Safeframe

ParamType
winWindow

Safeframe.getConf(win) ⇒ Array

Gets config of safeframe host.

Kind: static method of Safeframe

ParamType
winWindow

Safeframe.getSupport(win) ⇒ Array

Returns array of supported fields for sf.ext.

Kind: static method of Safeframe

ParamType
winWindow

Safeframe.getInView(win) ⇒ Number

Gets inview percentage of safeframe.

Kind: static method of Safeframe

ParamType
winWindow

Safeframe.getWinFocus(win) ⇒ Number

Returns if safeframe window has focus.

Kind: static method of Safeframe

ParamType
winWindow

Safeframe.getMetrics(win) ⇒ Array

Returns safeframe metrics.

Kind: static method of Safeframe

ParamType
winWindow

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

ParamType
elementElement
eventNameString
callbackfunction

Example

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

addEventListener(el, 'onLoad', cb);

appendHtml ⇒ Array

Deprecated

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
Note: This module is deprecated but remains for backwards compatibility; please use 'embedHtml' instead

ParamType
parentElElement
htmlString

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.

ParamTypeDescription
callbackfunction
targetWindowWindowYou can provide your own window reference for cases where you'd have an iframe.
isInteractiveOkBooleanInteractive 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.LOAD_ATTR and getExecutingScript.LOAD_STARTED.

Kind: inner method of getExecutingScript

ParamTypeDescription
validatorFuncfunction
testScriptHTMLScriptElementUsed for IoC/testing.

triggerEvent

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

ParamType
elementElement
eventNameString

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. For more info on eval visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

Returns: Object - evalResult

ParamType
scriptStringString

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

ParamTypeDescription
optionsObject
callbackfunctionExecuted 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.

ParamTypeDescription
urlsString | ArrayA single url, or a list of urls of scripts to load.
onLoadedfunctionCallback is executed when all scripts have finished loading.
onErrorfunctionCallback is executed if one or more scripts fail to load, and passed a single argument: the list of script urls that failed to load.
requestTimeoutNumberWhen 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
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

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

ParamTypeDescription
elElementThe HTML Element that contains the config defaults.
attrNameString
defaultsObject

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

perfMarker.provider ⇒ PerfMarker

Ties into an existing instance of PerfMarker.

Kind: static property of perfMarker

ParamTypeDescription
pkgNameStringThe name of the instance.

reportData

reportData.factory ⇒ ReportData

Create a new instance of the reportData module.

Kind: static property of reportData

ParamTypeDescription
baseURLStringBase url for reporting pixel info.
measurePerformanceInstanceMeasurePerformancePerformance instance to provide measurement timestamps.

reportData.provider ⇒ ReportData

Tie into an existing instance of the reportData module.

Kind: static property of reportData

Param
packageName

reportData~xhrTrack(trackURL) ⇒ String

Safari can't use tracking pixels on unload, but xhr is said to work. Caveat is it's a sync call so it hangs the browser a split second.

Kind: inner method of reportData

ParamType
trackURLString

reportData~imgTrack(trackURL)

This method makes a call to a url but does not actually draw a pixel to a page in any way. The image will be cleaned up by the browser easily because it's not referenced again past this point.

Kind: inner method of reportData

ParamTypeDescription
trackURLStringreturns {String}

reportData~isChrome() ⇒ boolean

Returns true if browser is Chrome; false otherwise

Kind: inner method of reportData

reportData~isSafari() ⇒ boolean

Returns true if browser is Safari; false otherwise

Kind: inner method of reportData

reportData~objectToQueryString(params) ⇒ String

Iterate over an object literal's properties and convert those to a string to be appended to a url

Kind: inner method of reportData

ParamTypeDescription
paramsObjectkey/value pairs to convert into a query string

reportData~isSendBeaconAvailable() ⇒ Boolean

Utility function to determine if sendBeacon is natively supprted

Kind: inner method of reportData

reportData~sendReport(url, isUnloadEvent, sendBeaconJsonString) ⇒ *

Sends data utilizing sendBeacon if selected and available

Kind: inner method of reportData

ParamTypeDescription
urlString
isUnloadEventBoolean
sendBeaconJsonStringStringJson formated string of data to send

format ⇒ String

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

ParamTypeDescription
componentsObjectThe 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.

ParamType
urlString

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
Returns: Boolean - returns whether CORS is supported

xhr~xhr(options, callback) ⇒ Object

Kind: inner method of xhr

ParamTypeDescription
optionsObject
callbackfunctionExecuted on response with the signature (status: Number, body: String).

Example

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

insertAfter(elemToInsert, targetElem)

Utility Function to Insert 'elemToInsert' after 'targetElem' in the DOM

Kind: global function

Param
elemToInsert
targetElem

isAScript(inputElem)

Returns true if inputElem is a script element; false otherwise

Kind: global function

ParamType
inputElemNode | Element

addToDom(elem, target)

Adds 'elem' to the DOM with target/parent element 'target' Scripts are treated differently than other elements because they have to be to work correctly

Kind: global function

Param
elem
target

customCloneScript(inputScriptElem, win) ⇒ Element

Clones a script element in a way that is compatible with dynamic DOM-ready loading Unfortunately, node.cloneNode() will not work in place of this function in this case nor can it be used inside this function

Kind: global function

ParamTypeDescription
inputScriptElemElementInput Script Element
winObject

cloneElem(elemToClone, win) ⇒ Node | Element

Creates a deep clone of the element passed in (with special logic for scripts) Scripts have to be handled differently because the script code will not execute unless they are processed this way

Kind: global function

ParamType
elemToClone
winObject

recursiveCloneAndAddToDom(inputElem, targetElem, win) ⇒ Node | Element

Recursively iterates through 'inputElem' child elements, creates clones of them, and attaches them to 'targetElem' Why? Because script elements (including nested ones) need to be cloned a specific way in order for the code they represent to be executed.

Kind: global function

ParamType
inputElemNode | Element
targetElemNode | Element
winObject

insertInlineHtmlString(htmlString, parentElem, win) ⇒ boolean

Adds 'htmlString' as a child to element 'parentElem' in a way that's safe to use after the document has been closed

Kind: global function

ParamTypeDescription
htmlStringStringHTML String to Add to the page
parentElemNode | ElementParent element to attach 'htmlString' as a child to; defaults to document.body
winObject

createInsContainer(win) ⇒ HTMLModElement

Returns an 'ins' element with a unique ID and class 'adlibs-ins'

Kind: global function

ParamType
winObject

docWriteHtmlString(htmlString, win) ⇒ boolean

Uses document.writeln to add an HTML string to the page

Kind: global function

ParamTypeDescription
htmlStringstringHTML String to Add to the page
winObject

isNativeFunction(value) ⇒ any

Returns true if a function is the native implementation; false otherwise

Kind: global function
Ref: https://davidwalsh.name/detect-native-function

ParamType
valuefunction

embedHtml(htmlString, parentElem, callback, win)

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

Kind: global function

ParamTypeDescription
htmlStringstring
parentElemHTMLElementParent element to attach 'htmlString' as a child to (this is only used if the document readyState is complete or interactive)
callbackfunctionCallback function
winObjectOptional window reference to write into

adlibs Developers


2.5.2

2 years ago

2.5.1

5 years ago

2.5.0

5 years ago

2.4.2

6 years ago

2.4.1

6 years ago

2.4.0

6 years ago

2.3.3

6 years ago

2.3.2

7 years ago

2.3.1

7 years ago

2.3.0

7 years ago

2.2.0

7 years ago

2.1.1

7 years ago

2.1.0

7 years ago

2.0.2

8 years ago

2.0.1

8 years ago

2.0.0

8 years ago

1.1.0

8 years ago

1.0.0

8 years ago