Members

(constant) getRequestClass

Return the "request class". This is a string value that may be set by the request processor (which has access to the original request from the browser). By default, the request class is undefined.

loadScriptCounter

loadScriptCounter is used as a key to the window.Mobify object handlers. We Want this outside the loadScript function so that it can be updated every loadScript is called with a new script to be embedded to the head tag.

(constant) parseCacheControl

Perform limited parsing of a Cache-Control header value, to extract the s-maxage and max-age values and return them.

(constant) SHOULD_PREVIEW_QUERY :string

The script path to the preview URL

Type:
  • string
Example
import {SHOULD_PREVIEW_QUERY} from 'progressive-web-sdk/dist/utils/preview-utils'

(constant) shouldLoadResource

Should the given resource be loaded by the SSR server?

(constant) ssrRenderingCompleteThunk

This thunk should be dispatched by UPWA code running server side when all rendering for the page has been completed.

(constant) ssrRenderingFailedThunk

This thunk should be dispatched by UPWA code running server side if an error occurs that prevents rendering of the page from completing.

(constant) supportedBrowsers

A list of supported browser objects and supported crawler bots consistent with Mobify's Platform Compatibility Matrix

Set immutable for link attributes.

Type:
  • object

Methods

browserSupportsMessaging(userAgent) → {Boolean}

Checks if the browser supports Messaging - specifically, whether it supports Mobify messaging, rather than W3C push notifications in general. Not all browsers that support push are supported by Mobify, since the support for the standards has evolved over time, and some older browsers have quirks that mean we consider them unsupported.

This function is Messaging-specific, but it's provided here in this SDK file so that it's usable by the loader, without requiring the loader to import yet another SDK module.

This function will work for a PWA and also in non-PWA (standalone) mode, so it will report true for browsers other than Chrome.

The checks here are a combination of browser capability checks and version checks for specific browsers. The minimum versions of browsers should align with the supported browser version in the Messaging server file https://github.com/mobify/pusheen/blob/master/backend/config.py

This function does not check for Safari APNS push messaging support.

Parameters:
Name Type Description
userAgent boolean

the userAgent to test - used for testing

Returns:
Type
Boolean
Example
import {browserSupportsMessaging} from 'progressive-web-sdk/dist/utils/utils'

browserSupportsMessaging('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:54.0) Gecko/20100101 Firefox/54.0')
// true

buildQueryString(query) → {String}

Build a query string

Parameters:
Name Type Description
query string

the query string

Returns:
Type
String
Example
import {buildQueryString} from 'progressive-web-sdk/dist/utils/utils'

buildQueryString('?n=John&n=Susan') // ?q=?n=John&n=Susan

calculateViewportSize() → {String}

Calculate the browsers viewportSize. This compares window.innerWidth against the breakpoints set by setBreakpoints. These breakpoints are treated as min-width for the purpose of determining the active breakpoint. For example, where BREAKPOINTS remains at it's default values, a window.innerWidth of 700, calculateViewportSize returns MEDIUM

For testing only, this function accepts a width parameter (since it's challenging to mock out window.innerWidth).

Returns:

the viewport sizes. Default return values include SMALL, MEDIUM, LARGE and XLARGE

Type
String
Example
calculateViewportSize(700) // => 'MEDIUM'

convertStateObjectToStateImmutable(stateObject) → {Object}

Takes a plain state object and converts it to an immutable state object. The result will match the shape required by the PWA reducers where the top-most object is a plain object, each branches contents is an immutable map except the UI branch which is a plain object and each branch inside is an immutable map

Parameters:
Name Type Description
stateObject Object

the plain state object

Returns:
Type
Object
Example
import {convertStateObjectToStateImmutable} from 'progressive-web-sdk/dist/utils/store-utils'

convertStateObjectToStateImmutable({test: {key1: 'value1', key2: 'value2'}}))
// { test: Map { "key1": "value1", "key2": "value2" } }

createAction(description, payloadArgNames, metaCreator) → {function}

This function wraps the redux-actions createAction function. It takes a description for the action (which must be unique!) and an array of names that will be used for the parameters in the action.

If no parameter names are passed in, the first argument (and only the first argument) to the action creator will be used directly as the payload.


We can pass an optional meta creator function to createAction. This function receives all of the arguments passed to the action creator, including those used for the payload, and creates a meta information object to be included in the action.

Currently we use meta information in actions for analytics. See createActionWithAnalytics below for a more convenient way to build actions with analytics information.

Parameters:
Name Type Description
description string

a unique name for the action

payloadArgNames array

an array of parameter names

metaCreator function

a meta creator

Returns:
Type
function
Example
import {createAction} from 'progressive-web-sdk/dist/utils/action-creation'

const addToCart = createAction('Add to cart', ['productId', 'quantity'])

dispatch(addToCart(65536, 2))

// dispatches an action with a payload of:
payload: {
    productId: 65536,
    quantity: 2
}

createActionWithAnalytics(description, payloadArgNames, analyticsType, analyticsPayloadCreator) → {function}

This function acts like createAction but simplifies the creation of the analytics meta payload. In addition to the action description and the payload argument names, it takes an analytics event type string and a function for creating the analytics payload.

The analytics payload creator receives all of the argments to the action creator, including all arguments included in the payload. In this way, we can use the payload information as part of the analytics payload, but also include additional information that is not relevant for the main action.

Parameters:
Name Type Description
description string

a unique name for the action

payloadArgNames array

an array of parameter names

analyticsType string

the type string for the analytics event

analyticsPayloadCreator function

A function that returns the analytics payload.

Returns:
Type
function
Example
import {createActionWithAnalytics} from 'progressive-web-sdk/dist/utils/action-creation'

// Imagine we are running an A/B tes on the color of the add to
// cart button. The colour of the button is irrelevant to the actual
// process of adding to the cart, but it is relevant to the analytics
// that are tracking the results of the A-B test. We can define our
// action in the following way:

const addToCart = createActionWithAnalytics(
    'Add to cart',
    ['id', 'quantity'],
    'cartAdd',
    (id, quantity, buttonColour) => ({id, quantity, buttonColour})
)

 // and then dispatch it with:

 dispatch(addToCart(15, 1, 'red'))
 // or
 dispatch(addToCart(15, 1, 'green'))

 // This would result in an action object with the form:
 {
     type: 'Add to cart',
     payload: {id: 15, quantity: 1},
     meta: {
         analytics: {
             type: 'cartAdd',
             payload: {id: 15, quantity: 1, buttonColour: 'green'}
         }
     }
 }

createTypedAction(description, type, key) → {function}

Create an action creator that typechecks its argument.

The action creator argument is passed unchanged as the payload if no key is passed, while if a key is provided the action creator argument is wrapped in an object under that key. This allows the action to set a specific key within the Redux store using mergePayload.

Parameters:
Name Type Description
description string

The description of the action (seen in dev tools)

type Runtype

The type to check the action argument against

key string

The key in the store to set with the payload

Returns:
  • The action creator.
Type
function
Example
import {createTypedAction} from 'progressive-web-sdk/dist/utils/action-creation'

decreaseVisitCountdowns() → {Object}

Retrieves visit countdowns from local storage, decreases each key's value by 1, then sets the value in local storage again.

Returns:
  • current visit countdowns
Type
Object
Example
import {decreaseVisitCountdowns} from 'progressive-web-sdk/dist/utils/messaging-state'

defer(fn)

Defer the execution of a function

Parameters:
Name Type Description
fn

the function to be deferred

documentWriteSupported() → {Boolean}

The purpose of this function is that when user is on a slow WiFi connections and unable to load page via document.write.

Returns:
Type
Boolean
Example
import {documentWriteSupported} from 'progressive-web-sdk/dist/utils/utils'

documentWriteSupported()
// true

extractPathFromURL(url, includeHash, includeQuery) → {String}

Converts a URL to the relative URL

Parameters:
Name Type Default Description
url string

the url to be converted (if it's already relative it will be returned as is)

includeHash bool false

indicates if the URL hash should be included in the relative URL returns

includeQuery bool true

indicates if the URL query should be included in the relative URL returns

Returns:
Type
String
Example
import {extractPathFromURL} from 'progressive-web-sdk/dist/utils/utils'

extractPathFromURL('http://www.mobify.com/test')
// /test

extractPathFromURL('https://localhost:8443/test?id=5#lower', true)
// /test?id=5#lower

extractPathFromURL('https://localhost:8443/test?id=5#lower', false)
// /test?id=5

extractPathFromURL('https://localhost:8443/test?id=5#lower', false, false)
// /test

formEncode(obj, prefix) → {String}

Form encodes nested URL query parameters using recursion Adapted from http://stackoverflow.com/questions/1714786/querystring-encoding-of-a-javascript-object

Parameters:
Name Type Description
obj object

the object to encode a Uniform Resource Identifier (URI)

prefix string

the prefix value to use to encode a URI

Returns:
Type
String
Example
import {formEncode} from 'progressive-web-sdk/dist/utils/fetch-utils'

getAssetUrl(path) → {string}

Get the URL that should be used to load an asset from the bundle.

This function is provided for use in UPWAs.

Parameters:
Name Type Description
path string

the path to the asset (relative to the build directory)

Returns:
Type
string

getBoundedValue(value, minimumValue, maximumValue) → {Number}

The function returns a value with an upper bound and a lower bound.

Parameters:
Name Type Description
value number

the value to set for bounded vlue

minimumValue number

the minium value

maximumValue number

the maxium value

Returns:
Type
Number
Example
import {getBoundedValue} from 'progressive-web-sdk/dist/utils/component-utils'

getBoundedValue(2, 5, 10)
// 5

getBreakpoints() → {Object}

Returns:

Dictionary of the registered breakpoints. Each breakpoint consists of a label (the keys) and a width (the values).

Type
Object

getBrowserSize(request) → {String}

Gets the name of the current viewport size based on the client's browser type. The return values can be configured with setBrowserSizeNames

Parameters:
Name Type Description
request Request

An ExpressJS Request

Returns:

The active browser size

Type
String
Example
getBrowserSize()

getBrowserSizeNames() → {Object}

Gets the breakpoint names for browsers across mobile, tablet and desktop. These object values should correspond to the values found in getBreakpoints(). The browser size name values can be configured with setBrowserSizeNames.

Returns:

The browser sizes for MOBILE, TABLET and DESKTOP

Type
Object

getBundleID(url) → {Promise}

Gets the currently deployed bundle ID Checks the ssrOptions and the URL path before making a request to get the bundleId from the header 'x-amz-meta-bundle'

Parameters:
Name Type Description
url string

Mobify url to request the 'x-amz-meta-bundle' header

Returns:
Type
Promise
Example
import {getBundleID} from 'progressive-web-sdk/dist/utils/debug-utils'

getBundleIDFromURL(url) → {string|null}

Parses the URL to get the currently deployed bundle

Parameters:
Name Type Description
url string

Url containing the bundleID

Returns:
Type
string | null
Example
import {getBundleIDFromURL} from 'progressive-web-sdk/dist/utils/debug-utils'

getChromeVersion(userAgent) → {Number}

Get the major version of Chrome and return it as an integer. If the browser isn't Chrome, return zero.

Parameters:
Name Type Description
userAgent string

the userAgent to test

Returns:
Type
Number
Example
import {getChromeVersion} from 'progressive-web-sdk/dist/utils/utils'

getChromeVersion('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36')
// 60

getCookie(name) → {String}

Gets the value of a specific cookie

Parameters:
Name Type Description
name string

The name of a cookie

Returns:
Type
String
Example
import {getCookie} from 'progressive-web-sdk/dist/utils/preview-utils'

document.cookie = 'testCookie=xyz'
getCookie('testCookie')
// xyz

getCookieValue(cookieName)

Get the document cookie value, it's based on regex courtesy of https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie.

Parameters:
Name Type Description
cookieName string

the value of cookie name

Example
import {getCookieValue} from 'progressive-web-sdk/dist/utils/utils'

const cookieValue = 'World'
document.cookie = `test2=${cookieValue}`
getCookieValue('test2') // World

getDeployTarget() → {String}

Return the identifier of the deploy target where this UPWA is running. For the local development SSR Server, the value returned will normally be an empty string (''). However, if the environment variable DEPLOY_TARGET is defined, it will set the value returned by this function, so that the local development server can be used for testing code that checks the value.

Returns:
Type
String

getDisplayName(WrappedComponent) → {String}

Display the name of the component

Parameters:
Name Type Description
WrappedComponent function

the name of the component

Returns:
Type
String
Example
import {getDisplayName} from 'progressive-web-sdk/dist/utils/component-utils'

class AnotherMockComponent extends React.Component {
    render() {
         return (<div>More mock html</div>)
    }
}

getDisplayName(AnotherMockComponent) // "AnotherMockComponent"

getFirefoxVersion(userAgent) → {Number}

Get the major version of Firefox. If the browser isn't Firefox, then return zero

Parameters:
Name Type Description
userAgent string

the userAgent to test

Returns:
Type
Number
Example
import {getFirefoxVersion} from 'progressive-web-sdk/dist/utils/utils'

getFirefoxVersion('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:54.0) Gecko/20100101 Firefox/54.0')
// 54

getHashForString(text) → {string}

Given a string, return a hash for that string. The hash is usable as an etag, or any other context where a summary hash of a string is required.

Parameters:
Name Type Description
text string

the string to be hashed

Returns:

the hash of that string, in hexadecimal

Type
string

getMobifyScriptSrc() → {string}

Get the src of the Mobify script loading the page E.g. loader.js, adaptive.js

Returns:
Type
string
Example
import {getMobifyScriptSrc} from 'progressive-web-sdk/dist/utils/debug-utils'

getPageCount() → {Number}

Gets the current page count from local storage.

Returns:
  • The current page count, or 0 if not found in storage
Type
Number
Example
import {getPageCount} from 'progressive-web-sdk/dist/utils/messaging-state'

getPath(object) → {String}

Returns a path given a location object.

Parameters:
Name Type Description
object object

a location object from React Router

Properties:
Name Type Description
object.pathname string

the path name

object.search string

the search query

Returns:
  • the path and search concatenated together
Type
String
Example
import {getPath} from 'progressive-web-sdk/dist/utils/utils'

const object = {
    pathname: 'product',
    search: '?post=1234&action=edit'
}
getPath(object) // product?post=1234&action=edit

getProjectIDandTargetFromURL(mobifyUrl) → {Object}

Get the target and projectId from the Mobify URL serving the Mobify tag

Parameters:
Name Type Description
mobifyUrl string

URL serving the mobify tag

Returns:
Type
Object
Example
import {getProjectIDandTargetFromURL} from 'progressive-web-sdk/dist/utils/debug-utils'

getProxyConfigs() → {Array.<Object>}

Return the set of proxies configured for a UPWA. The result is an array of objects, each of which has 'protocol' (either 'http' or 'https'), 'host' (the hostname) and 'path' (the path element that follows "/mobify/proxy/", defaulting to 'base' for the first proxy, and 'base2' for the next).

Each object also has a 'proxy' property, which is an ExpressJS function that can be called to proxy a request to the target for that object. This uses all the standard SSR proxy handling, including rewriting of request and response headers. This can be used in contexts such as the SSRServer requestHook to proxy requests. Do NOT use the proxy function from UPWA code. It will not work.

Ideally, we would return a clone of the configuration, but in the interests of performance we may return a reference. Modifying the value will have no effect on the actual proxy setup, and there should be no need to ever do that.

This function will work correctly whether called from UPWA code or from SSR code (for example, from the requestHook or responseHook of the SSR Server).

Returns:
Type
Array.<Object>

getPWAType() → {String}

Determines which PWA the app is running as

Returns:

if isStandalone is true returns 'PWA:standalone', otherwise returns 'PWA'

Type
String

getSSRTimingInformation() → {Object|null}

Get the SSR Timing information and format it to be displayed

Returns:
Type
Object | null
Example
import {getSSRTimingInformation} from 'progressive-web-sdk/dist/utils/debug-utils'

getTextFrom($element, selector) → {String}

Get text from an element.

Parameters:
Name Type Description
$element node

a jQuery object

selector string
Returns:
Type
String
Example
import {getTextFrom} from 'progressive-web-sdk/dist/utils/parser-utils'

getTextFrom($('<div><div class="class-name"><span>Text</span></div></div>'), '.class-name')
// Text

getURL(location) → {String}

Returns a full URL given a location object.

Parameters:
Name Type Description
location object

a location object from React Router

Returns:
  • the full URL for the given location
Type
String
Example
// window.location.origin = https://www.mobify.com/

import {getURL} from 'progressive-web-sdk/dist/utils/utils'

const pathName = 'product'
const searchQuery = '?post=1234&action=edit'
const object = {
    pathname: pathName,
    search: searchQuery
}
getURL(object) // https://www.mobify.com/product?post=1234&action=edit

getVisitCountdowns() → {Object}

Gets the visit countdowns object from local storage

Returns:
  • current visit countdowns
Type
Object
Example
import {getVisitCountdowns} from 'progressive-web-sdk/dist/utils/messaging-state'

initStorage() → {Object}

Creates local instances of PushMessaginStore and Logger, for use in other methods. Call this first before any other methods.

Returns:
Type
Object
Example
import {initStorage} from 'progressive-web-sdk/dist/utils/messaging-state'

iOSBrowser(userAgent) → {Boolean}

Return true if the given useragent is of a browser running on iOS. We do this to allow detection of all iOS/webkit browsers in one test.

Parameters:
Name Type Description
userAgent string

the userAgent to test

Returns:
Type
Boolean
Example
import {iOSBrowser} from 'progressive-web-sdk/dist/utils/utils'

iOSBrowser('Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1')
// true

isAndroidBrowser(userAgent) → {Boolean}

Return true if the given useragent is of a browser running on Android.

Parameters:
Name Type Description
userAgent string

the userAgent to test

Returns:
Type
Boolean
Example
import {isAndroidBrowser} from 'progressive-web-sdk/dist/utils/utils'

isAndroidBrowser('Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19')
// true

isChrome68OrHigher(userAgent) → {Boolean}

Check if Chrome version is 68 or higher. Non-Chrome browsers will always return false.

Parameters:
Name Type Description
userAgent string

the userAgent to test

Returns:
Type
Boolean
Example
import {getChromeVersion} from 'progressive-web-sdk/dist/utils/utils'

isChrome68OrHigher('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36')
// 60

isCrawler() → {Boolean}

Returns true if the current user agent suggest it is a web crawler.

Returns:
Type
Boolean
Example
import {isCrawler} from 'progressive-web-sdk/dist/utils/utils'

isCrawler()
// true

isDataURL(url) → {bool}

Indicate is the URL passed in is a Data URL URI scheme.

Parameters:
Name Type Description
url string

the url to be tested

Returns:
  • indicates if the URL is a data URL
Type
bool
Example
import {isDataURL} from 'progressive-web-sdk/dist/utils/utils'

isDataURL('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')

isFirefoxBrowser(userAgent) → {Boolean}

Checks if the user is on Samsung Browser

Parameters:
Name Type Description
userAgent string

the userAgent to test

Returns:
Type
Boolean
Example
import {isFirefoxBrowser} from 'progressive-web-sdk/dist/utils/utils'

isFirefoxBrowser('Mozilla/5.0 ... Firefox')
// true

isLocalStorageAvailable() → {Boolean}

Checks if local storage is available in the current environment.

Returns:
Type
Boolean
Example
import {isLocalStorageAvailable} from 'progressive-web-sdk/dist/utils/utils'

isLocalStorageAvailable()
// true

isMessagingSupported() → {Boolean}

Return true if and only if both the enabled and supported flags in window.Progressive.Messaging are truthy. These flags are set by the PWA loader, so they may be tested at any time after the PWA is loaded. If this function is called before the loader runs, it will return false. If this function returns false, then Messaging is not available at all, and no UI for it need be (or should be) shown. If this function returns true, then Messaging has been configured in the PWA and the browser supports it, but the user may have blocked notifications, or not be subscribed, or be running in a mode (such as incognito) where subscriptions can't be created. Information on the subscription status is provided when the Promise stored in window.Progressive.MessagingClientInitPromise is resolved - see the https://docs.mobify.com/progressive-web/latest/components/#!/PushMessagingController for details.

Returns:
Type
Boolean
Example
import {isMessagingSupported} from 'progressive-web-sdk/dist/utils/messaging'

isMessagingSupported()
// true

isOrIsNotBusy()

Debug log helper to avoid duplicating strings

isPreview() → {Boolean}

Checks if the user is in preview mode

Returns:
Type
Boolean
Example
import {isPreview} from 'progressive-web-sdk/dist/utils/preview-utils'

isPreview()
// true

isSamsungBrowser(userAgent) → {Boolean}

Checks if the user is on Samsung Browser

Parameters:
Name Type Description
userAgent string

the userAgent to test

Returns:
Type
Boolean
Example
import {isSamsungBrowser} from 'progressive-web-sdk/dist/utils/utils'

isSamsungBrowser('Mozilla/5.0 ... SamsungBrowser')
// true

isSessionStorageAvailable() → {Boolean}

Checks if session storage is available in the current environment.

Returns:
Type
Boolean
Example
import {isSessionStorageAvailable} from 'progressive-web-sdk/dist/utils/utils'

isSessionStorageAvailable()
// true

isStandalone() → {Boolean}

This util is designed for use only when the app first launches in standalone mode. The window.matchMedia check may fail on some versions of chrome even if the app is in standalone mode and after the app launches and the user has navigated elsewhere the URL may not contain ?homescreen=1 anymore.

Using this util outside of when the app launches may produce false negatives

If you need to check if the app is in standalone mode use the key stored in the app branch of the redux store instead of this util.

Returns:
Type
Boolean
Example
import {isStandalone} from 'progressive-web-sdk/dist/utils/utils'

isStandalone()
// true

isStorageAvailable(storage) → {Boolean}

Checks if the given storage type is available.

Parameters:
Name Type Description
storage Storage
See:
Returns:
Type
Boolean
Example
import {isStorageAvailable} from 'progressive-web-sdk/dist/utils/utils'

isSubscribedToChannel(isSubscribed, channels, channelNameopt) → {Boolean}

Helper method to determine if the visitor is subscribed to this channel name

Parameters:
Name Type Attributes Description
isSubscribed boolean

whether the visitor is currently subscribed to any channel

channels array

The list of channels the visitor is subscribed to

channelName string <optional>

The channel name for this ask instance; if undefined then assumes broadcast channel

Returns:
  • If the user is subscribed to the optional channel name
Type
Boolean
Example
import {isSubscribedToChannel} from 'progressive-web-sdk/dist/utils/messaging'

isSubscribedToChannel(true, ['channel1', 'channel2']) // true

isSubscribedToChannel(false, ['channel1', 'channel2'], 'channel1') // false

isUniveral() → {boolean}

Check if this is a Universal PWA

Returns:
Type
boolean
Example
import {isUniveral} from 'progressive-web-sdk/dist/utils/debug-utils'

isUniversal() → {boolean}

If code is running in a UPWA, return true. If it's running in any other context (PWA, AMP, etc), return false.

Returns:
Type
boolean

isUsingMobifyPreview() → {boolean}

Checks the Mobify object to see if the page is in preview mode

Returns:
Type
boolean
Example
import {isUsingMobifyPreview} from 'progressive-web-sdk/dist/utils/debug-utils'

isV8Tag() → {Boolean}

Checks if the loader has been loaded via a V8+ tag, the version 8 of the Mobify Tag.

Returns:
Type
Boolean
Example
import {isV8Tag} from 'progressive-web-sdk/dist/utils/preview-utils'

isV8Tag()
// true

loadPreview()

Writes the preview script to the document

Example
import {loadPreview} from 'progressive-web-sdk/dist/utils/preview-utils'

loadPreview()
// true

loadScript(id, src, isAsync, docwrite, onload, onerror)

Writes script tag to the document, head tag

Parameters:
Name Type Default Description
id string

The id for script

src string

The path to script

isAsync boolean true

Writes an asynchronous function

docwrite boolean false

Writes a string of text to a document

onload function

The onload callback function

onerror boolean

Rejects the function

Example
import {loadScript} from 'progressive-web-sdk/dist/utils/utils'

loadScript({
    id: 'loadScriptTest1',
    src: 'loadScriptTest1src'
})

loadScriptAsPromise(id, src, onload, isAsync, rejectOnError, docwrite)

Instantiates a promise to write a script tag to the document head tag. The promise is resolved by the script's onload callback.

Parameters:
Name Type Default Description
id string

The id for script

src string

The path to script

onload function

The onload callback function

isAsync boolean true

Writes an asynchronous function

rejectOnError boolean true

Rejects the function on error

docwrite boolean false

Writes a string of text to a document

Example
import {loadScriptAsPromise} from 'progressive-web-sdk/dist/utils/utils'

loadScriptAsPromise({
    id: 'loadScriptTest1',
    src: 'loadScriptTest1src'
})

loadUPWA(options, overridesopt)

Load the PWA. Must be called with the required options (in an object) from the project's ssr-loader.js file.

Parameters:
Name Type Attributes Description
options Object
Properties
Name Type Attributes Default Description
messagingSiteId String <optional>

If supplied, messaging is enabled (assuming the browser supports it) and the given string is the messaging site_id.

mobifyPropertyId String

The project's property id (previously called the 'projectSlug').

debug Boolean <optional>
false

true to enable some debug logging, falsy if no debug output should be enabled.

overrides Object <optional>

allows override (mocking) of the functions called by loadUPWA, for testing. Mocking out imported functions is problematic: the overrides object allows us to do it selectively.

loadWorker(pwaMode, messagingEnabled, cacheHashManifest, skipLoader)

Load the service worker.

In nonPWA mode, this will be called on every page. This is safe; to quote https://developers.google.com/web/fundamentals/getting-started/primers/service-workers: "You can call register() every time a page loads without concern; the browser will figure out if the service worker is already registered or not and handle it accordingly".

Note, though, that this assumes the URL returned by getServiceWorkerURL doesn't change between pages. If it does, then the worker will be re-registered with a different URL, causing it to restart.

Parameters:
Name Type Description
pwaMode Boolean

true if the worker should be loaded in PWA mode, false if not

messagingEnabled Boolean

true if messaging should be enabled

cacheHashManifest object

The cacheHashManifest typically found in window.Progressive

skipLoader Boolean

true if the service worker can be loaded directly without the use of the service worker loader

Returns:

Promise. true when the worker is loaded and ready, false if the worker fails to register, load or become ready.

Logger(prefix) → {Logger}

Simple module to enable logging under debug conditions only. Defaults to determining debug status based on preview, which is shared across all instances

Parameters:
Name Type Default Description
prefix string ''

Appends the given prefix to any logging statements - defaults to empty string

Returns:
Type
Logger

makeFormEncodedRequest(url, data, options) → {Object}

Make a request given the provided url and options, form-encoding the data into the body of the request.

Parameters:
Name Type Description
url string

a url to make the request

data object

data to use in the formEncode function

options object

options for the make form encoded request

Returns:
Type
Object
Example
import {makeFormEncodedRequest} from 'progressive-web-sdk/dist/utils/fetch-utils'

makeJsonEncodedRequest(url, data, options) → {Object}

Make a request to a URL with the request body data encoded in stringified JSON

Parameters:
Name Type Description
url string

the url to make request

data object

the object to pass in JSON

options object

options for the make JSON encoded request

Returns:
Type
Object
Example
import {makeJsonEncodedRequest} from 'progressive-web-sdk/dist/utils/fetch-utils'

makeRequest(url, options) → {Object}

Makes a fetch request to the provided url. The credentials fetch option is always set to same-origin.

Parameters:
Name Type Description
url string

the url to make request

options object

options for the make request

Returns:
Type
Object
Example
import {makeRequest} from 'progressive-web-sdk/dist/utils/fetch-utils'

mergePayload(state, payload) → {Object}

This performs a deep merge of the state and payload. It returns a copy of the merged state.

Parameters:
Name Type Description
state object

object or array state

payload object

data to be merged into the state

Returns:
Type
Object
Example
import {mergePayload} from 'progressive-web-sdk/dist/utils/reducer-utils'

mergePayloadSkipList(state, payload) → {Object}

This performs a merge of the state with the payload by using skipListsMerger as the merge function.

Parameters:
Name Type Description
state object

object or array state

payload object

data to be merged into the state

Returns:
Type
Object
Example
import {mergePayloadSkipList} from 'progressive-web-sdk/dist/utils/reducer-utils'

normalizePhone(value, previousValue) → {String}

Output the phone number format eg. "(123) 456-7890". Based on the example here in "normalizePhone.js" section in Redux Form.

Parameters:
Name Type Description
value string

Expects a phone number numberic string

previousValue string

The value of the field on which you have placed the normalizer before the most recent change

Returns:
Type
String
Example
import {normalizePhone} from 'progressive-web-sdk/dist/utils/normalize-utils'

normalizePhone(6044315987)
// (604) 431-5987

parseButton($button) → {Object}

Parse button that outputs button attributes: children, type, name, value, and disabled.

Parameters:
Name Type Description
$button node

a jQuery object

Returns:
Type
Object
Example
import {parseButton} from 'progressive-web-sdk/dist/utils/parser-utils'

parseButton($(<button type="submit" name="Submit" value="test" disabled>Button</button>))
// {type: 'submit', children: 'Button', name: 'Submit', value: 'test', disabled: true}

parseImage($img) → {Object}

Parse image that outputs image attributes: title, alt, and src.

Parameters:
Name Type Description
$img node

a jQuery object

Returns:
Type
Object
Example
import {parseImage} from 'progressive-web-sdk/dist/utils/parser-utils'

parseImage($('<img src="equality.svg" title="Equality Now!" alt="An equals sign" />'))
// {src: 'equality.svg', title: 'Equality Now!', alt: 'An equals sign'}

parseOption($option) → {Object}

Parse option to use in select element, option attributes includes: key, value, selected and text.

Parameters:
Name Type Description
$option node

a jQuery object

Returns:
Type
Object
Example
import {parseOption} from 'progressive-web-sdk/dist/utils/parser-utils'

parseOption($('<option value="test" selected>Option</option>'))
// {key: 'test', value: 'test', selected: true, text: 'Option'}

parsePageMeta($, $response) → {Object}

Parse page's metadata that includes title, description and keywords.

Parameters:
Name Type Description
$ node

an instance of jQuery

$response node

a jQuery object

Returns:
Type
Object
Example
import {parsePageMeta} from 'progressive-web-sdk/dist/utils/parser-utils'

const $test = $('head')
$test.append(`<title>Page Title</title>`)
$test.append(`<meta name="description" content="Page description"/>`)
$test.append(`<meta name="keywords" content="Keyword1, Keyword2, Keyword3"/>`)
parsePageMeta($, $test)
// pageMeta: {title: "Page Title", description: "Page description", keywords: "Keyword1, Keyword2, Keyword3"}

parseSelect($, $select) → {Object}

Parse select that outputs select attributes: name and options.

Parameters:
Name Type Description
$ node

an instance of jQuery

$select node

a jQuery object

Returns:
Type
Object
Example
import {parseSelect} from 'progressive-web-sdk/dist/utils/parser-utils'

parseSelect($, $('<select name="tester"><option value="Jest" selected>Jest</option><option value="Mocha">Mocha</option></select>'))
// {name: 'test', options: [{key: 'Jest', value: 'Jest', selected: true, text: 'Jest'}, {key: 'Mocha', value: 'Mocha', selected: false, text: 'Mocha'}]}

Parse link that outputs link attributes: href, text and title.

Parameters:
Name Type Description
$link node

a jQuery object

Returns:
Type
Object
Example
import {parseTextLink} from 'progressive-web-sdk/dist/utils/parser-utils'

parseTextLink($('<a href="/test.html" title="Test">Click Here!</a>'))
// {href: '/test.html', text: 'Click Here!', title: 'Test'}

Writes a link element to the document. The link element includes charset, href and rel attributes. "charset" attribute is set with "utf-8", "rel" attribute is set with "prefetch", and you set "href" with object param with href property.

Parameters:
Name Type Description
object object
Properties:
Name Type Description
object.href string

the href path

Example
import {prefetchLink} from 'progressive-web-sdk/dist/utils/messaging'

prefetchLink({href: 'path'})

preloadSWAmp(pwaMode, messagingEnabled, cacheHashManifest) → {Boolean}

Preload the service worker when user visits AMP site.

Parameters:
Name Type Description
pwaMode Boolean

true if the worker should be loaded in PWA mode, false if not

messagingEnabled Boolean

true if the messaging should be enabled false if not

cacheHashManifest JSON

updated hash manifest json object PWA mode, false if not

Returns:

true when the requested for SW installation from an AMP page, false elsewhere.

Type
Boolean

preventDesktopSiteFromRendering()

Inserts a <plaintext> tag to document, it gets written immediately after the Mobify tag.

Example
import {preventDesktopSiteFromRendering} from 'progressive-web-sdk/dist/utils/utils'

preventDesktopSiteFromRendering()

renderOrHydrate(component, store, rootEl, callbackopt)

Render and mount a React component. Or, hydrate a React component for a client side UPWA instead. When the React application renders client side or hydrates, the Redux state is dispatched to indicate that setIsServerSideOrHydratingFlag is false.

Parameters:
Name Type Attributes Description
component Object

The React component to mount to the root element

store Object

An instance of the application's redux store. It is used internally to dispatch actions.

rootEl Object

The "root element" DOM node for an element that the react application will be mounted to

callback function <optional>

The callback function invoked after rendering or hydration is finished.

Example
const store = configureStore({})
const rootEl = document.getElementsByClassName('react-target')[0]
renderOrHydrate(<Router store={store} />, store, rootEl)

rfc1123(date) → {String}

Return the given date as an RFC1123-format string, suitable for use in a Set-Cookie or Date header. The result is always in UTC.

Parameters:
Name Type Description
date Date
Returns:
Type
String

runningServerSide() → {*|boolean}

For code that doesn't have access to the store, this function provides a defined way to check whether code is running server-side or not.

This is named runningServerSide rather than isServerSide to avoid it being confused with the isServerSide selector.

Returns:
  • true if running server-side, false if not
Type
* | boolean

sendPerformanceEvent(tracker)

Sends a performance timing event through the provided sandy tracker

Parameters:
Name Type Description
tracker Object

setBreakpoints(breakpoints) → {Object}

Parameters:
Name Type Description
breakpoints Object

A dictionary of breakpoint names and their values. Values must be integers. Use setBreakpoints to configure which labels the calculateViewportSize utility function returns.

Returns:

A non-referencial copy of the newly configured breakpoints object

Type
Object
Example
setBreakpoints({
    MEDIUM: 700,
    CUSTOM_BREAKPOINT: 1440
})

setBrowserSizeNames(BrowserSizes)

Set the breakpoints names for browsers across mobile, tablet and desktop. The object values should correspond to the values found in the BREAKPOINTS object returned by getBreakpoints().

Parameters:
Name Type Description
BrowserSizes Object

A dictionary of browser sizes as a strings

Properties
Name Type Description
MOBILE String

The breakpoint name assigned to mobile devices. Defaults to 'SMALL'

TABLET String

The breakpoint name assigned to tablet devices. Defaults to 'MEDIUM'

DESKTOP String

The breakpoint name assigned to desktop devices. Defaults to 'LARGE'

Example
setBrowserSizeNames({
    MOBILE: 'SMALL'
    TABLET: 'MEDIUM'
    DESKTOP: 'LARGE'
})

setCustomContent(customPath) → {function}

This merges the payload into the state at the designated customPath. Regardless of what's added to the customPath, the final node in the path will always be treated as custom. set to provided value.

Parameters:
Name Type Description
customPath array | string

the name of custom path

Returns:
Type
function
Example
import {setCustomContent} from 'progressive-web-sdk/dist/utils/reducer-utils'

const myReducer = handleActions({
    // Merges to state.custom
    [someAction0.action]: setCustomContent(),

    // Merges to state.products.custom
    [someAction1.action]: setCustomContent('products'),

    // merges to state.products.categories.custom
    [someAction2.action]: setCustomContent(['products', 'categories'])
})

setPageCount(pageCount) → {Number}

Sets the page count in storage using the provided pageCount argument

Parameters:
Name Type Description
pageCount number

The page count to set in storage

Returns:
  • The provided pageCount argument
Type
Number
Example
import {setPageCount} from 'progressive-web-sdk/dist/utils/messaging-state'

setPerformanceValues()

Sets peformance timing values on window. Progressive.

setVisitCountdownsInStorage(countdowns) → {Object}

Sets the provided countdowns object in local storage.

Parameters:
Name Type Description
countdowns object

The visit countdowns object to set in storage

Returns:
  • The provided countdowns argument
Type
Object
Example
import {setVisitCountdownsInStorage} from 'progressive-web-sdk/dist/utils/messaging-state'

shouldAsk(logger, props) → {Boolean}

Determines whether an ask should be shown, based on the following conditions:

  1. Messaging Client is ready and says the visitor is eligible for push notifications (i.e. has not revoked push notification permissions or has granted them already)
  2. The visitor is subscribed, but has not yet subscribed to this channel
  3. There is no visit countdown in progress for this channel (or it was disabled)
  4. The visitor has seen the required number of pages on the site (which may be disabled)
Parameters:
Name Type Description
logger function

Is bound to the correct logger; for testing

props object

Properties used to determine whether to ask

Returns:
  • true if "ask" can be shown, false otherwise
Type
Boolean
Example
import {shouldAsk} from 'progressive-web-sdk/dist/utils/messaging'

shouldPreview() → {Boolean}

This function is used to check whether the application should, or should not, run preview. Because preview should only run once, if the application has already done so then this function will return false.

Returns:
Type
Boolean
Example
import {shouldPreview} from 'progressive-web-sdk/dist/utils/preview-utils'

shouldPreview()
// true

skipListsMerger(a, b) → {Object}

Ensures the new list is always used when merging Maps that contain lists.

Parameters:
Name Type Description
a object

first object to merge

b object

second object to merge

See:
Returns:
Type
Object
Example
import {skipListsMerger} from 'progressive-web-sdk/dist/utils/reducer-utils'

splitFullName(fullname) → {Object}

Transform full name into an object

Parameters:
Name Type Description
fullname String

First and last name

Returns:
Type
Object
Example
import {splitFullName} from 'progressive-web-sdk/dist/utils/utils'

splitFullName(`John Smith`)
// {firstname: 'John', lastname: 'Smith'}

ssrRenderingComplete(appState, responseOptionsopt) → {Promise}

This function should be called by UPWA code running server side when all rendering for the page has been completed. It must be passed the current application state.

This function should be called once and once only by UPWA code. Once it has been called, further execution of the UPWA code may not be possible.

Parameters:
Name Type Attributes Description
appState object

the application store

responseOptions object <optional>

optional values to configure the HTTP response

Properties
Name Type Attributes Description
statusCode Number <optional>

the HTTP status code for the response (defaults to 200 for all pages except the configured pageNotFoundURL, which uses 404).

headers Object <optional>

an object containing header values to be set on the response. The object keys are the header names, and the object values may be strings (for single-value headers) or arrays of strings (for multi-value headers). You may also choose to set response headers in the responseHook function of the SSRServer. Any header values passed to ssrRenderingComplete are set before responseHook is called.

suppressBody Boolean <optional>

if the statusCode is one that means the response body is redundant (e.g., 301 or 302), then you should pass suppressBody: true so that the response doesn't include any of the body (which can be very large).

Returns:
Type
Promise

ssrRenderingCompleted() → {boolean}

This function may be called by UPWA code running server-side to determine if ssrRenderingComplete has been called.

If called client-side, this function will always return a falsy value.

Returns:
  • true if ssrRenderingComplete has been called, false if not.
Type
boolean

ssrRenderingFailed(error)

This function may be called by UPWA code running server side if an error occurs that prevents rendering of the page from completing.

In general, if the UPWA is unable to fetch data for a page, it is preferable to render the page partially and call ssrRenderingComplete. This function should only be called in the event of an error that prevents any rendering from being done.

Parameters:
Name Type Description
error Object | String

an Error or an error string

startVisitCountdown(visitsToWait, channelName) → {Object}

Adds the optionally provided channel name, or "default" to the visit countdowns object, with the provided visitsToWait argument, which is then set in local storage.

Parameters:
Name Type Default Description
visitsToWait number

The number of visits to wait before showing an ask again

channelName string DEFAULT_CHANNEL

Optional channel name (default is 'broadcast')

Returns:
  • Current visit countdowns
Type
Object
Example
import {startVisitCountdown} from 'progressive-web-sdk/dist/utils/messaging-state'

stripEvent(fn) → {function}

Wraps an action creator function so that the React synthetic action is not passed in. This is necessary to avoid spurious warnings from the React code.

Parameters:
Name Type Description
fn function

an action creator function

Returns:
  • the wrapped action creator
Type
function
Example
import {stripEvent} from 'progressive-web-sdk/dist/utils/utils'

trackFirstPaints()

Track First Paint and First Contentful Paint for PWA and non-PWA

triggerSandyAppStartEvent(pwaMode, aJsSlug, platform) → {Promise.<*>}

A setTimeout wraps this trigger function in order to control the exact timing that any tracking pixels are downloaded as the app initializes. More specifically, downloading of any tracking pixels should not delay the downloading of any other scripts (i.e. service workers, etc.)

Parameters:
Name Type Description
pwaMode Boolean

true for PWA mode, false for nonPWA mode. This affects the set of dimensions configured on the tracker, and whether an initial timing point is collected (it's done in PWA mode only).

aJsSlug String

The A.js slug for the project

platform String

The platform dimension to set. This should be: PWA, PWA:standalone, UPWA or nonPWA. If no platform string is provided one will be determined based on the value of pwaMode.

Returns:

resolved when setup is complete and any app start events have been sent.

Type
Promise.<*>

typecheck(type, value) → {*}

Validates a value against a runtype. If the value does not match the provided runtype, this function will still output the value, but it will also log a "Type check failed" error to the console.

Parameters:
Name Type Description
type object

A valid runtype instance. See runtypes for details: https://www.npmjs.com/package/runtypes

value *

The value being verified as the type provided by the type param

Returns:
  • Returns the value, as passed into the value param
Type
*
Example
import {typecheck} from 'progressive-web-sdk/dist/utils/typechecking'
import {Number} from 'runtypes'

const id = 'myId'
typecheck(Number, id) // => 'myId'
// This will log an error to the console:
//
//     "Type check failed: ${error}
//     Value: 'myId'"

updateState() → {Object}

Updates and retrieves the current page count and visit countdowns from local storage, decreasing visit countdowns if page count was not found.

Returns:
  • pageCount: the current page count
    • visitCountdowns: the current visit countdowns
Type
Object
Example
import {updateState} from 'progressive-web-sdk/dist/utils/messaging-state'

urlToBasicPathKey(url) → {String}

Converts a full URL to the preferred format for keying the redux store, i.e. only the path (without query string)

Parameters:
Name Type Description
url string

The url to be converted

Returns:
Type
String
Example
import {urlToBasicPathKey} from 'progressive-web-sdk/dist/utils/utils'

urlToBasicPathKey('http://www.mobify.com/test')
// /test

urlToPathKey(url) → {String}

Converts a full URL to the preferred format for keying the redux store, i.e. the path and query string

Parameters:
Name Type Description
url string

The url to be converted

Returns:
Type
String
Example
import {urlToPathKey} from 'progressive-web-sdk/dist/utils/utils'

urlToPathKey('http://www.mobify.com/test')
// /test

uuid() → {String}

Outputs a UUID. Credit to a user on Stack Overflow for this approach: https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript

Returns:
Type
String
Example
import uuid from from 'progressive-web-sdk/dist/utils/uuid-utils'

uuid()
// '5eeba8b4-96a8-458a-bafa-a1765790bad1'

validateCCExpiry(ccExpiry) → {Boolean}

Checks to see if a credit card has expired given the expiry date.

Parameters:
Name Type Description
ccExpiry string

The numeric date string with the format "mmyy"

Returns:
Type
Boolean
Example
import {validateCCExpiry} from 'progressive-web-sdk/dist/utils/validation'

validateCCExpiry('0922')
// true

validateCCNumber(ccNumber) → {Boolean}

Validates the given credit card number

Parameters:
Name Type Description
ccNumber string

The credit card number to validate

Returns:
Type
Boolean
Example
import {validateCCNumber} from 'progressive-web-sdk/dist/utils/validation'

validateCCNumber('375556917985515')
// true

validateFullName(fullName) → {Boolean}

Validates that the given full name has at least two "words" (regex '\w') separated by at least one space

Parameters:
Name Type Description
fullName string

The full name to validate

Returns:
Type
Boolean
Example
import {validateFullName} from 'progressive-web-sdk/dist/utils/validation'

validateFullName('John Smith')
// true

validatePageNumber(page, count) → {Number}

Verify if page number is valid If valid, return page number If not valid, return first or last page number

Parameters:
Name Type Default Description
page number

input page parameter to be verified

count number false

optional parameter indicate total page count

Returns:
Type
Number
Example
import {validatePageNumber} from 'progressive-web-sdk/dist/utils/utils'

validatePageNumber(100, 10) // 10

validatePageNumber(-6) // 1

validatePostalCode(postalCode, countryId) → {Boolean}

Validates the given postal code according to the rules for the given country

Parameters:
Name Type Description
postalCode string

The postal code to validate

countryId string

The country to validate for (country is any ISO-3166 "alpha-2" code)

Returns:
Type
Boolean
Example
import {validatePostalCode} from 'progressive-web-sdk/dist/utils/validation'

validatePostalCode('A1A 1A1', 'CA')
// true

Type Definitions

ParsedHost

Type:
  • Object
Properties:
Name Type Description
host String

The host (10.10.10.10:port), which includes the port (if any)

hostname String

The hostname (10.10.10.10), which excludes the port

port String

The host's port

isIPOrLocalhost Boolean

Whether the hostname is an IP or localhost