Custom template APIs

Core APIs

These APIs work with sandboxed JavaScript to build custom templates in Google Tag Manager. Each API is added with a require() statement, e.g.:

const myAPI = require('myAPI');

addConsentListener

Registers a listener function to execute when the state of the specified consent type changes.

The given listener will be invoked every time the state for the specified consent type changes from denied to granted or from granted to denied. A consent type with no state is considered granted, so the listener won't be called if an unset consent type is updated to granted. Listener functions will be in charge of ensuring their code runs the appropriate number of times.

Example:

const isConsentGranted = require('isConsentGranted');
const addConsentListener = require('addConsentListener');

if (!isConsentGranted('ad_storage')) {
  let wasCalled = false;
  addConsentListener('ad_storage', (consentType, granted) => {
    if (wasCalled) return;
    wasCalled = true;

    const cookies = getMyCookies();
    sendFullPixel(cookies);
  });
}

Syntax

addConsentListener(consentType, listener)

Parameters

Parameter Type Description
consentType string The consent type to listen for state changes on.
listener function The function to run when the state of the specified consent type changes.

When a listener is invoked, it will be passed the consent type that is being changed and the new value of that consent type:

Parameter Type Description
consentType string The consent type that is being changed.
granted boolean A boolean which is true if the specified consent type is being changed to granted.

Associated permissions

access_consent permission with read access for the consent type.


addEventCallback

The addEventCallback API allows you to register a callback function that will be invoked at the end of an event. The callback will be invoked when all the tags for the event have executed, or if an in page event timeout is reached. The callback is passed two values, the id of the container that invokes the function and an object that contains information about the event.

Syntax

addEventCallback(callback)

Parameters

Parameter Type Description
callback function The function to invoke at the end of the event.

The eventData object contains the following data:

Key Name Type Description
tags Array An array of tag data objects. Every tag that fired during the event will have an entry in this array. The tag data object contains the tag's ID (id), its execution status (status), and its execution time (executionTime). The tag data will also include additional tag metadata that was configured on the tag.

Example

addEventCallback(function(ctid, eventData) {
  logToConsole('Tag count for container ' + ctid + ': ' + eventData['tags'].length);
});

Associated permissions

read_event_metadata


aliasInWindow

The aliasInWindow API lets you create an alias (e.g. window.foo = window.bar), which helps to support certain tags that require aliasing. Assigns the value in the window object found at the fromPath to the key in the window object at the toPath. Returns true if successful, false otherwise.

Syntax

aliasInWindow(toPath, fromPath)

Parameters

Parameter Type Description
toPath string A dot-separated path into the window object where a value should be copied to. All components in the path up to the last component must already exist in the window object.
fromPath string A dot-separated path into window to the value to copy. If the value does not exist, the operation will fail.

Example

aliasInWindow('foo.bar', 'baz.qux')

Associated permissions

access_globals is required for both toPath and fromPath; toPath requires write access, fromPath requires read access.


callInWindow

Allows you to call functions from a path off the window object, in a policy- controlled way. Calls the function at the given path in window with the given arguments and returns the value. If the return type can't be directly mapped to a type supported in sandboxed JavaScript, undefined will be returned. The eight types supported in sandboxed JavaScript are null, undefined, boolean, number, string, Array, Object, and function. If the given path does not exist, or does not reference a function, undefined will be returned.

Syntax

callInWindow(pathToFunction, argument [, argument2,... argumentN])

Parameters

Parameter Type Description
pathToFunction string A dot-separated path to the function in window to call.
args * Arguments to be passed to the function.

Associated permissions

access_globals with execute permission enabled.


callLater

Schedules a call to a function to occur asynchronously. The function will be called after the current code returns. This is equivalent to setTimeout(<function>, 0).

Syntax

callLater(function)

Parameters

Parameter Type Description
function function The function to call.

copyFromDataLayer

Returns the value currently assigned to the given key in the data layer: The value found at the given key if it's a primitive type, function, or object literal, or undefined otherwise.

Syntax

copyFromDataLayer(key[, dataLayerVersion])

Parameters

Parameter Type Description
key string The key in the format of "a.b.c".
dataLayerVersion number The optional data layer version. The default value is 2. It is strongly discouraged to use the value 1.

Associated permissions

read_data_layer


copyFromWindow

Copies a variable from window object. If the value in window can't be directly mapped to a type supported in sandboxed JavaScript, undefined will be returned. The eight types supported in sandboxed JavaScript are null, undefined, boolean, number, string, Array, Object, and function. Returns the fetched (and coerced) value.

Syntax

copyFromWindow(key)

Parameters

Parameter Type Description
key string The key in the window to copy the value of.

Associated permissions

access_globals


createArgumentsQueue

Creates a queue that is populated with argument objects, in support of tag solutions that require it.

Creates a function in global scope (i.e. window), using the fnKey argument (same semantics as createQueue). After the function is created, this API then creates an array in window (if it doesn't already exist) using the arrayKey argument.

When the function created under fnKey is called, it pushes its arguments object onto the array created under arrayKey. The API's return value is the function created under fnKey.

This function requires the read and write setting for fnKey and arrayKey on the access_globals permission.

Example:

const gtag = createArgumentsQueue('gtag', 'dataLayer');
gtag('set', {'currency': 'USD'});

Syntax

createArgumentsQueue(fnKey, arrayKey)

Parameters

Parameter Type Description
fnKey string The path in window where the function is set, if it does not already exist. This argument supports standard dot notation. If the key's path does not exist, an exception is thrown. That is, if fnKey is 'one.two', it will throw an exception.
arrayKey string The path in window where the array is set, if it does not already exist. This argument supports standard dot notation. If the key's path does not exist, an exception is thrown. That is, if arrayKey is 'one.two', and there is no global object named 'one', it will throw an exception.

Associated permissions

access_globals


createQueue

Creates an array in window (if it doesn't already exist) and returns a function that will push values onto that array.

This function requires the read and write setting for arrayKey on the access_globals permission.

Example:

const dataLayerPush = createQueue('dataLayer');
dataLayerPush({'currency': 'USD'}, {'event': 'myConversion'});

Syntax

createQueue(arrayKey)

Parameters

Parameter Type Description
arrayKey string The key in window where the array is set, if it does not already exist. This argument supports standard dot notation. If the key's path does not exist, an exception is thrown. For example, if arrayKey is 'one.two', and there is no global object named 'one', it will throw an exception.

Associated permissions

access_globals


decodeUri

Decodes any encoded characters in the provided URI. Returns a string that represents the decoded URI. Returns undefined when provided with invalid input.

Example:

const decode = require('decodeUri');

const decodedUrl = decode(data.encodedUrl);
if (decodedUrl) {
  // ...
}

Syntax

decodeUri(encoded_uri)

Parameters

Parameter Type Description
encoded_uri string A URI that has been encoded by encodeUri() or by other means.

Associated permissions

None.


decodeUriComponent

Decodes any encoded characters in the provided URI component. Returns a string that represents the decoded URI component. Returns undefined when provided with invalid input.

Example:

const decode = require('decodeUriComponent');

const decodedUrl = decode(data.encodedUrl);
if (decodedUrl) {
  // ...
}

Syntax

decodeUriComponent(encoded_uri_component)

Parameters

Parameter Type Description
encoded_uri_component string A URI component that has been encoded by encodeUriComponent() or by other means.

Associated permissions

None.


encodeUri

Returns an encoded Uniform Resource Identifier (URI) by escaping special characters. Returns a string that represents the provided string encoded as a URI. Returns undefined when provided with invalid input (a lone surrogate).

Example:

sendPixel('https://www.example.com/' + encodeUri(pathInput));

Syntax

encodeUri(uri)

Parameters

Parameter Type Description
uri string A complete URI.

Associated permissions

None.


encodeUriComponent

Returns an encoded Uniform Resource Identifier (URI) by escaping special characters. Returns a string that represents the provided string encoded as a URI. Returns undefined when provided with invalid input (a lone surrogate).

Example:

sendPixel('https://www.example.com/?' + encodeUriComponent(queryInput));

Syntax

encodeUriComponent(str)

Parameters

Parameter Type Description
str string A component of a URI.

Associated permissions

None.


fromBase64

The fromBase64 API lets you to decode strings from their base64 representation. Returns undefined when provided with invalid input.

Syntax

fromBase64(base64EncodedString)

Parameters

Parameter Type Description
base64EncodedString string Base64 encoded string.

Example

const fromBase64 = require('fromBase64');

const greeting = fromBase64('aGVsbG8=');
if (greeting === 'hello') {
  // ...
}

Associated permissions

None


generateRandom

Returns a random number (integer) within the given range.

Syntax

generateRandom(min, max)

Parameters

Parameter Type Description
min number Minimum potential value of the returned integer.
max number Maximum potential value of the returned integer.

Associated permissions

None.


getContainerVersion

Returns an object containing data about the current container. The returned object has the following fields:

{
  containerId: string,
  debugMode: boolean,
  environmentName: string,
  environmentMode: boolean,
  previewMode: boolean,
  version: string,
}

Example

const getContainerVersion = require('getContainerVersion');
const sendPixel = require('sendPixel');

if (query('read_container_data')) {
  const cv = getContainerVersion();

  const pixelUrl = 'https://pixel.com/' +
    '?version=' + cv.version +
    '&envName=' + cv.environmentName +
    '&ctid=' + cv.containerId +
    '&debugMode=' + cv.debugMode +
    '&previewMode=' + cv.previewMode;
  if (query('send_pixel', pixelUrl)) {
    sendPixel(pixelUrl);
  }
}

Syntax

getContainerVersion();

Associated permissions

read_container_data


getCookieValues

Returns the values of all cookies with the given name.

Syntax

getCookieValues(name[, decode])

Parameters

Parameter Type Description
name string Name of the cookie.
decode boolean Controls whether the cookie values are to be decoded with JavaScript's decodeURIComponent(). Defaults to true.

Associated permissions

get_cookies


getQueryParameters

Returns the first or all of the parameters for the current URL's queryKey. Returns the first value from the queryKey or an Array of values from the queryKey.

Syntax

getQueryParameters(queryKey[, retrieveAll])

Parameters

Parameter Type Description
queryKey string The key to read from the query parameters.
retrieveAll boolean Whether to retrieve all the values.

For example, if the current URL is https://example.com/path?var=foo&var1=foo1&var=foo2&var=foo, then:

  • getQueryParameters('var') == 'foo'
  • getQueryParameters('var', false) == 'foo'
  • getQueryParameters('var', null) == 'foo'
  • getQueryParameters('var', true) == ['foo', 'foo2', 'foo']

Associated permissions

get_url must allow the query component, and must specify the queryKey in the allowed query keys (or allow any query key.)


getReferrerQueryParameters

The getReferrerQueryParameters API acts the same way as getQueryParameters, except it acts on the referrer instead of the current URL. Returns the first or all of the parameters for the given referrer's queryKey. Returns the first value from the queryKey or an Array of values from the queryKey.

Syntax

getReferrerQueryParameters(queryKey[, retrieveAll])

Parameters

Parameter Type Description
queryKey string The key to read from the query parameters.
retrieveAll boolean Whether to retrieve all the values.

For example, if the referrer URL is https://example.com/path?var=foo&var1=foo1&var=foo2&var=foo, then:

  • getReferrerQueryParameters('var') == 'foo'
  • getReferrerQueryParameters('var', false) == 'foo'
  • getReferrerQueryParameters('var', null) == 'foo'
  • getReferrerQueryParameters('var', true) == ['foo', 'foo2', 'foo']

Associated permissions

get_referrer must allow the query component, and must specify the queryKey in the allowed query keys (or allow any query key.)


getReferrerUrl

Given a component type, the API reads the document object for the referrer and returns a string that represents a portion of the referrer. If no component is specified, full referrer URL is returned.

Syntax

getReferrerUrl([component])

Parameters

Parameter Type Description
component string The component to return from the URL. Can be one of the following: protocol, host, port, path, query, extension. If component is undefined, null, or doesn't match one of these components, the entire URL will be returned.

Associated permissions

get_referrer must allow the query component, and must specify the queryKey in the allowed query keys (or allow any query key.)


getTimestamp

Deprecated. Prefer getTimestampMillis.

Returns a number that represents the current time in milliseconds since Unix epoch, as returned by Date.now().

Syntax

getTimestamp();

Associated permissions

None.


getTimestampMillis

Returns a number that represents the current time in milliseconds since Unix epoch, as returned by Date.now().

Syntax

getTimestampMillis();

Associated permissions

None.


getType

Returns a string describing the given value's type. Unlike typeof, getType differentiates between array and object.

Syntax

getType(data.someField)

Notes

The following table lists the strings returned for each input value.

Input Value Result
undefined 'undefined'
null 'null'
true 'boolean'
12 'number'
'string' 'string'
{ a: 3 } 'object'
[ 1, 3 ] 'array'
(x) => x + 1 'function'

Associated permissions

None.


getUrl

Returns a string that represents all or a portion of the current URL, given a component type, and some configuration parameters.

Syntax

getUrl(component)

Parameters

Parameter Type Description
component string The component to return from the URL. Must be one of: protocol, host, port, path, query, extension, fragment. If component is undefined, null, or doesn't match one of these components, the entire href value will be returned.

Associated permissions

get_url


gtagSet

Pushes a gtag set command to the data layer, to be processed as soon as possible after the current event and any tags it triggered are finished processing (or the tag processing timeout is reached). The update is guaranteed to be processed in this container before any queued items in the data layer queue.

For example, if called by a tag fired on Consent Initialization, the update will be applied before the Initialization event is processed. Examples would be ads_data_redaction being set to true or false or url_passthrough being set to true or false.

Examples:

const gtagSet = require('gtagSet');

gtagSet({
  'ads_data_redaction': true,
  'url_passthrough': true,
});

Syntax

gtagSet(object)

Parameters

Parameter Type Description
Object object An object that updates the global state for its containing properties.

Associated permissions

write_data_layer checks write permission to dataLayer for all the specified keys. If input to gtagSet is a plain object, the API will check for write permission to all the flattened keys inside that object, e.g. for gtagSet({foo: {bar: 'baz'}}), the API will check for write permission to foo.bar.

If the input to gtagSet is a key and some non-plain object value, the API will check for write permission to that key, e.g. for gtagSet('abc', true) , the API will check for write permission to 'abc'.

Note that if there is a cycle in the input object, only keys before reaching the same object will be checked.


injectHiddenIframe

Adds an invisible iframe to the page.

Callbacks are given as function instances, and are wrapped in JavaScript functions that call through to them.

Syntax

injectHiddenIframe(url, onSuccess)

Parameters

Parameter Type Description
url string The URL to be used as the value of the iframe's src attribute.
onSuccess function Called when the frame loads successfully.

Associated permissions

inject_hidden_iframe


injectScript

Adds a script tag to the page to load the given URL asynchronously. The callbacks are given as function instances, and are wrapped in JavaScript functions that call through to them.

Syntax

injectScript(url, onSuccess, onFailure[, cacheToken])

Parameters

Parameter Type Description
url string The address of the script to be injected.
onSuccess function Called when the script loads successfully.
onFailure function Called when the script fails to load.
cacheToken string Optional string used to indicate the given URL should be cached. If this value is specified, only one script element will be created to request the JavaScript. Any additional attempts to load will result in the given onSuccess and onFailure methods being queued until the script loads.

Associated permissions

inject_script


isConsentGranted

Returns true if the specified consent type is granted.

Consent for a particular consent type is considered to be granted if the consent type has been set to 'granted' or not set at all. If the consent type is set to any other value it will be considered not granted.

The Tag Manager user interface for tag settings will offer an option to always fire. If a tag with always fire turned on uses this API, consent is considered granted and true will be returned, regardless of the actual state of consent.

Example:

const isConsentGranted = require('isConsentGranted');

if (isConsentGranted('ad_storage')) {
  sendFullPixel();
} else {
  sendPixelWithoutCookies();
}

Syntax

isConsentGranted(consentType)

Parameters

Parameter Type Description
consentType string The consent type to check the state of.

Associated permissions

access_consent permission with read access for the consent type.


JSON

Returns an object that provides JSON functions.

The parse() function parses a JSON string to construct the value or object described by the string. If the value cannot be parsed (e.g. malformed JSON), the function will return undefined. If the input value is not a string, the input will be coerced to a string.

The stringify() function converts the input into a JSON string. If the value cannot be parsed (e.g. the object has a cycle), the method will return undefined.

Syntax

JSON.parse(stringInput)
JSON.stringify(value);

Parameters

JSON.parse

Parameter Type Description
stringInput any The value to convert. If the value is not a string, the input will be coerced to a string.

JSON.stringify

Parameter Type Description
value any The value to convert.

Example

const JSON = require('JSON');

// The JSON input string is converted to an object.
const object = JSON.parse('{"foo":"bar"}');

// The input object is converted to a JSON string.
const str = JSON.stringify({foo: 'bar'});

localStorage

Returns an object with methods for accessing local storage.

Syntax

const localStorage = require('localStorage');

// Requires read access for the key. Returns null if the key does not exist.
localStorage.getItem(key);

// Requires write access for the key. Returns true if successful.
localStorage.setItem(key, value);

// Requires write access for the key.
localStorage.removeItem(key);

Associated permissions

access_local_storage

Example

const localStorage = require('localStorage');
if (localStorage) {
  const value = localStorage.getItem('my_key');
  if (value) {
    const success = localStorage.setItem('my_key', 'new_value');
    if (success) {
      localStorage.removeItem('my_key');
    }
  }
}

logToConsole

Logs arguments to the browser console.

Syntax

logToConsole(obj1 [, obj2,... objN])

Parameters

Parameter Type Description
obj1 [, obj2,... objN] any Arguments

Associated permissions

logging


makeInteger

Converts the given value to a number (integer).

Syntax

makeInteger(value)

Parameters

Parameter Type Description
value any The value to convert.

Associated permissions

None.


makeNumber

Converts the given value to a number.

Syntax

makeNumber(value)

Parameters

Parameter Type Description
value any The value to convert.

Associated permissions

None.


makeString

Returns the given value as a string.

Syntax

makeString(value)

Parameters

Parameter Type Description
value any The value to convert.

Associated permissions

None.


makeTableMap

Converts a simple table object with two columns to a Map. This is used to change a SIMPLE_TABLE template field with two columns into a more manageable format.

For example, this function could convert a table object:

[
  {'key': 'k1', 'value': 'v1'},
  {'key': 'k2', 'value': 'v2'}
]

into a Map:

{
  'k1': 'v1',
  'k2': 'v2'
}

Returns an Object: The converted Map if key-value pairs have been added to it, or null otherwise.

Syntax

makeTableMap(tableObj, keyColumnName, valueColumnName)

Parameters

Parameter Type Description
tableObj List The table object to convert. It's a list of maps where each Map represents a row in the table. Each property name in a row object is the column name, and the property value is the column value in the row.
keyColumnName string Name of the column whose values will become keys in the converted Map.
valueColumnName string Name of the column whose values will become values in the converted Map.

Associated permissions

None.


Math

An object providing Math functions.

Syntax

const Math = require('Math');

// Retrieve the absolute value.
const absolute = Math.abs(-3);

// Round the input down to the nearest integer.
const roundedDown = Math.floor(3.6);

// Round the input up to the nearest integer.
const roundedUp = Math.ceil(2.2);

// Round the input to the nearest integer.
const rounded = Math.round(3.1);

// Return the largest argument.
const biggest = Math.max(1, 3);

// Return the smallest argument.
const smallest = Math.min(3, 5);

// Return the first argument raised to the power of the second argument.
const powerful = Math.pow(3, 1);

// Return the square root of the argument.
const unsquared = Math.sqrt(9);

Parameters

Math functions parameters are converted to numbers.

Associated permissions

None.


Object

Returns an object that provides Object methods.

The keys() method provides the Standard Library Object.keys() behavior. It returns an array of a given object's own enumerable property names in the same order that a for...in... loop would. If the input value is not an object, it will be coerced to an object.

The values() method provides the Standard Library Object.values() behavior. It returns an array of a given object's own enumerable property values in the same order that a for...in... loop would. If the input value is not an object, it will be coerced to an object.

The entries() method provides the Standard Library Object.entries() behavior. It returns an array of a given object's own enumerable property [key, value] pairs in the same order that a for...in... loop would. If the input value is an not an object, it will be coerced to an object.

The freeze() method provides the Standard Library Object.freeze() behavior. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, and the values of existing properties from being changed. freeze() returns the same object that was passed in. A primitive or null argument will be treated as if it were a frozen object, and will be returned.

The delete() method provides the Standard Library delete operator behavior. It removes the given key from the object unless the object is frozen. Like the Standard Library delete operator, it returns true if the first input value (objectInput) is an object that is not frozen even if the second input value (keyToDelete) specifies a key that does not exist. It returns false in all other cases. However, it differs from the Standard Library delete operator in the following ways:

  • keyToDelete cannot be a dot-delimited string that specifies a nested key.
  • delete() cannot be used to remove elements from an array.
  • delete() cannot be used to remove any properties from the global scope.

Syntax

Object.keys(objectInput)
Object.values(objectInput)
Object.entries(objectInput)
Object.freeze(objectInput)
Object.delete(objectInput, keyToDelete)

Parameters

Object.keys

Parameter Type Description
objectInput any The object whose keys to enumerate. If the input is not an object, it will be coerced to an object.

Object.values

Parameter Type Description
objectInput any The object whose values to enumerate. If the input is not an object, it will be coerced to an object.

Object.entries

Parameter Type Description
objectInput any The object whose key/value pairs to enumerate. If the input is not an object, it will be coerced to an object.

Object.freeze

Parameter Type Description
objectInput any The object to freeze. If the input is not an object, it will be treated as a frozen object.

Object.delete

Parameter Type Description
objectInput any The object whose key to delete.
keyToDelete string The top-level key to delete.

Example

const Object = require('Object');

// The keys of an object are enumerated in an array.
const keys = Object.keys({foo: 'bar'});

// The values of an object are enumerated in an array.
const values = Object.values({foo: 'bar'});

// The key/value pairs of an object are enumerated in an array.
const entries = Object.entries({foo: 'bar'});

// The input object is frozen.
const frozen = Object.freeze({foo: 'bar'});

// The key is removed from the input object.
const obj1 = {deleteme: 'value'};
Object.delete(obj1, 'deleteme');
// Only a top-level key can be specified as the key to delete.
const obj2 = {nested: {key: 'value'}};
Object.delete(obj2, 'nested.key'); // This has no effect.
Object.delete(obj2.nested, 'key'); // This deletes the nested key.

parseUrl

Returns an object that contains all of a given URL's component parts, similar to the URL object.

This API will return undefined for any malformed URL. For properly formatted URLs, fields not present in the URL string will have a value of an empty string, or in the case of searchParams, an empty object.

The returned object will have the following fields:

{
  href: string,
  origin: string,
  protocol: string,
  username: string,
  password: string,
  host: string,
  hostname: string,
  port: string,
  pathname: string,
  search: string,
  searchParams: Object<string, (string|Array)>,
  hash: string,
}

Example

const parseUrl = require('parseUrl');

const urlObject = parseUrl('https://abc:xyz@example.com:8080/foo?param=val%2Cue#bar');

Syntax

parseUrl(url);

Parameters

Parameter Type Description
url string The full url that will be parsed.

Associated permissions

None.


queryPermission

Query the allowed and narrowed permissions. Returns a boolean: true if a permission is granted, false otherwise.

Syntax

queryPermission(permission, functionArgs*)

Parameters

Parameter Type Description
permission string Name of the permission.
functionArgs any Function arguments vary based on the permission being queried. See Function Arguments below.

Function Arguments

sendPixel, injectScript, injectHiddenIframe: The second parameter should be a URL string.

writeGlobals, readGlobals: The second parameter should be the key being written or read.

readUrl: No additional arguments are necessary to query whether the whole URL can be read. To query whether a given component can be read, pass the component name as the second argument:

if (queryPermission('readUrl','port')) {
  // read the port
}

To check whether a specific query key is readable, pass the query key as the third parameter:

if (queryPermission('readUrl','query','key')) {
  getUrlComponent(...);
}

Associated permissions

None.


readCharacterSet

Returns the value of document.characterSet.

Syntax

readCharacterSet()

Parameters

None.

Associated permissions

read_character_set


readTitle

Returns the value of document.title.

Syntax

readTitle()

Parameters

None.

Associated permissions

read_title


require

Imports a built-in function by name. Returns a function or an object that can be called from your program. Returns undefined when the browser does not support the built-in function.

Syntax

require(name)

Parameters

Parameter Type Description
name string The name of the function to import.

Example

const getUrl = require('getUrl');
const url = getUrl();

Associated permissions

None.


sendPixel

Makes a GET request to a specified URL endpoint.

Syntax

sendPixel(url, onSuccess, onFailure)

Parameters

Parameter Type Description
url string Where to send the pixel.
onSuccess function Called when the pixel successfully loads. Note: even if the request successfully sends, browsers may require a valid image response in order to run onSuccess.
onFailure function Called when the pixel fails to load. Note: even if the request successfully sends, onFailure may run if the server does not return a valid image response.

Associated permissions

send_pixel


setCookie

Sets or deletes the cookie with the specified name, value, and options.

Syntax

setCookie(name, value[, options, encode])

Parameters

Parameter Type Description
name string Name of the cookie.
value string Value of the cookie.
options object Specifies the Domain, Path, Expires, Max-Age, Secure, and SameSite attributes. (See Options, below.)
encode boolean Controls whether the cookie value is to be encoded with JavaScript's encodeURIComponent(). Defaults to true.

Options

  • Domain: set by options['domain'] property, if present. Set this value to 'auto' to try to write the cookie using the broadest possible domain, based on the document location. If that fails, it will try successively narrower subdomains. If all of those fail, it will try to write the cookie without a domain. If no value is set, this will try to write the cookie without a domain specified. Note: when a cookie without a domain specified is written to document.cookie, the user agent will default the cookie's domain to the host of the current document location.
  • Path: set by options['path'], if present. When a cookie without a path specified is written to document.cookie, the user agent will default the cookie's path to the path of the current document location.
  • Max-Age: set by options['max-age'], if present.
  • Expires: set by options['expires'], if present. If present, this must be a UTC-formatted date string. Date.toUTCString() can be used to format a Date for this parameter.
  • Secure: set by options['secure'], if present.
  • SameSite: set by options['samesite'], if present.

Associated permissions

set_cookies


setDefaultConsentState

Pushes a default consent update to the data layer, to be processed as soon as possible after the current event and any tags it triggered are finished processing (or the tag processing timeout is reached). The update is guaranteed to be processed in this container before any queued items in the data layer. Learn more about consent.

Example:

const setDefaultConsentState = require('setDefaultConsentState');

setDefaultConsentState({
  'ad_storage': 'denied',
  'analytics_storage': 'granted',
  'third_party_storage': 'denied',
  'region': ['US-CA'],
  'wait_for_update': 500
});

Syntax

setDefaultConsentState(consentSettings)

Parameters

Parameter Type Description
consentSettings object An object that defines the default state for the specified consent types.

The consentSettings object is a mapping of arbitrary consent type strings to one of 'granted' or 'denied'. It supports the following values:

Key Name Type Description
consentType string The value for each consent type can be set to `'granted'` or `'denied'`. Any value other than `'granted'` will be treated as `'denied'`. Setting the value to `undefined` won't have any effect on its previous value.
region Array An optional array of region codes specifying which region the consent settings apply to. Region codes are expressed using country and/or subdivisions in ISO 3166-2 format.
wait_for_update number Specifies a millisecond value to control how long to wait before data is sent. Used with consent tools that load asynchronously.

Associated permissions

access_consent permission with write access for all consent types in the consentSettings object.


setInWindow

Sets the given value in window at the given key. By default this method won't set the value in the window if there is already a value present. Set overrideExisting to true to set the value in the window regardless of the presence of an existing value. Returns a boolean: true if the value was set successfully, and false otherwise.

Syntax

setInWindow(key, value, overrideExisting)

Parameters

Parameter Type Description
key string The key in window to place the value at.
value * The value to set in window.
overrideExisting boolean The flag indicating that value should be set in window, regardless if there's a value there or not.

Associated permissions

access_globals


sha256

Calculates the SHA-256 digest of the input and invokes a callback with the digest encoded in base64, unless the options object specifies a different output encoding.

Example:

sha256('inputString', (digest) => {
  sendPixel('https://example.com/collect?id=' + digest);
  data.gtmOnSuccess();
}, data.gtmOnFailure);

sha256('inputString', (digest) => {
  sendPixel('https://example.com/collect?id=' + digest);
  data.gtmOnSuccess();
}, data.gtmOnFailure, {outputEncoding: 'hex'});

Syntax

sha256(input, onSuccess, onFailure = undefined, options = undefined)

Parameters

Parameter Type Description
input string The string to calculate the hash for.
onSuccess function Called with the resulting digest, encoded in base64, unless the options object specifies a different output encoding.
onFailure function Called if an error occurs while calculating the digest, or if the browser does not have native support for sha256. The callback is called with an object containing the name of the error, and the message.
options object Optional options object to specify the output encoding. If specified, the object should contain the key outputEncoding with value as one of base64 or hex.

Associated permissions

None.


templateStorage

Returns an object with methods for accessing template storage. Template storage allows data to be shared across executions of a single template. Data stored in template storage persists for the lifetime of the page.

Syntax

const templateStorage = require('templateStorage');

templateStorage.getItem(key);

templateStorage.setItem(key, value);

templateStorage.removeItem(key);

// Deletes all stored values for the template.
templateStorage.clear();

Associated permissions

access_template_storage

Example

const templateStorage = require('templateStorage');
const sendPixel = require('sendPixel');

// Ensure sendPixel is called only once per page.
if (templateStorage.getItem('alreadyRan')) {
  data.gtmOnSuccess();
  return;
}

templateStorage.setItem('alreadyRan', true);

sendPixel(
  data.oncePerPagePixelUrl,
  data.gtmOnSuccess,
  () => {
    templateStorage.setItem('alreadyRan', false);
    data.gtmOnFailure();
  });

toBase64

The toBase64 API lets you to encode a string into a base64 representation.

Syntax

toBase64(input)

Parameters

Parameter Type Description
input string String to encode.

Example

const toBase64 = require('toBase64');

const base64Hello = toBase64('hello');

Associated permissions

None


updateConsentState

Pushes a consent update to the data layer, to be processed as soon as possible after the current event and any tags it triggered are finished processing (or the tag processing timeout is reached). The update is guaranteed to be processed in this container before any queued items in the data layer. Learn more about consent.

Example:

const updateConsentState = require('updateConsentState');

updateConsentState({
  'ad_storage': 'granted',
  'analytics_storage': 'denied',
  'third_party_storage': 'granted',
});

Syntax

updateConsentState(consentSettings)

Parameters

Parameter Type Description
consentSettings object An object that updates the state for the specified consent types.

The consentSettings object is a mapping of arbitrary consent type strings to one of 'granted' or 'denied'. It supports the following values:

Key Name Type Description
consentType string The value for each consent type can be set to 'granted' or 'denied'. Any value other than 'granted' will be treated as 'denied'. Setting the value to 'undefined' won't have any effect on its previous value.

Associated permissions

access_consent permission with write access for all consent types in the consentSettings object.


Test APIs

These APIs work with sandboxed JavaScript tests to build tests for custom templates in Google Tag Manager. These test APIs do not need a require() statement. Learn more about custom template tests.


assertApi

Returns a matcher object that can be used to fluently make assertions about the given API.

Syntax

assertApi(apiName)

Parameters

Parameter Type Description
apiName string The name of the api to check; same string as passed to require().

Matchers

  • Subject.wasCalled()
  • Subject.wasNotCalled()
  • Subject.wasCalledWith(...expected)
  • Subject.wasNotCalledWith(...expected)

Examples

assertApi('sendPixel').wasCalled();
assertApi('getUrl').wasNotCalled();
assertApi('makeNumber').wasCalledWith('8');
assertApi('setInWindow').wasNotCalledWith('myVar', 'theWrongValue');

assertThat

The assertThat API is modeled after Google's [Truth] library. It returns an object that can be used to fluently make assertions about a subject's value. An assertion failure will immediately stop the test and mark it as failed. However, a failure in one test will not affect other test cases.

Syntax

assertThat(actual, opt_message)

Parameters

Parameter Type Description
actual any The value to use in the fluent checks.
opt_message string Optional message to print if the assertion fails.

Matchers

Matcher Description
isUndefined() Asserts that the subject is undefined.
isDefined() Asserts that the subject is not undefined.
isNull() Asserts that the subject is null.
isNotNull() Asserts that the subject is not null.
isFalse() Asserts that the subject is false.
isTrue() Asserts that the subject is true.
isFalsy() Asserts that the subject is falsy. Falsy values are undefined, null, false, NaN, 0, and '' (empty string).
isTruthy() Asserts that the subject is truthy. Falsy values are undefined, null, false, NaN, 0, and '' (empty string).
isNaN() Asserts that the subject is the value NaN.
isNotNaN() Asserts that the subject is any value besides NaN.
isInfinity() Asserts that the subject is positive or negative Infinity.
isNotInfinity() Asserts that the subject is any value besides positive or negative Infinity.
isEqualTo(expected) Asserts that the subject is equal to the given value. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
isNotEqualTo(expected) Asserts that the subject is not equal to the given value. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
isAnyOf(...expected) Asserts that the subject is equal to one of the given value. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
isNoneOf(...expected) Asserts that the subject is not equal to any of the given values. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
isStrictlyEqualTo(expected) Asserts that the subject is strictly equal (===) to the given value.
isNotStrictlyEqualTo(expected) Asserts that the subject is not strictly equal (!==) to the given value.
isGreaterThan(expected) Asserts that the subject is greater than (>) the given value in an ordered comparison.
isGreaterThanOrEqualTo(expected) Asserts that the subject is greater than or equal to (>=) the given value in an ordered comparison.
isLessThan(expected) Asserts that the subject is less than (<) the given value in an ordered comparison.
isLessThanOrEqualTo(expected) Asserts that the subject is less than or equal to (<=) the given value in an ordered comparison.
contains(...expected) Asserts that the subject is an array or string that contains all of the given values in any order. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
doesNotContain(...expected) Asserts that the subject is an array or string that contains none of the given values. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
containsExactly(...expected) Asserts that the subject is an array that contains all of the given values in any order and no other values. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
doesNotContainExactly(...expected) Asserts that the subject is an array that has contains a different set of values from the given values in any order. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
hasLength(expected) Asserts that the subject is an array or string with the given length. The assertion always fails if the value is not an array or string.
isEmpty() Asserts that the subject is an array or string that is empty (length = 0). The assertion always fails if the value is not an array or string.
isNotEmpty() Asserts that the subject is an array or string that is not empty (length > 0). The assertion always fails if the value is not an array or string.
isArray() Asserts that the type of the subject is an array.
isBoolean() Asserts that the type of the subject is a boolean.
isFunction() Asserts that the type of the subject is a function.
isNumber() Asserts that the type of the subject is a number.
isObject() Asserts that the type of the subject is an object.
isString() Asserts that the type of the subject is a string.

Examples

assertThat(undefined).isUndefined();
assertThat(id, 'ID must be defined').isDefined();
assertThat(null).isNull();
assertThat(undefined).isNotNull();
assertThat(true).isTrue();
assertThat(false).isFalse();
assertThat(1).isTruthy();
assertThat('').isFalsy();
assertThat(1/0).isInfinity();
assertThat(0).isNotInfinity();
assertThat(-'foo').isNaN();
assertThat(100).isNotNaN();
assertThat(sentUrl).isEqualTo('https://endpoint.example.com/?account=12345');
assertThat(category).isNotEqualTo('premium');
assertThat(5).isAnyOf(1, 2, 3, 4, 5);
assertThat(42).isNoneOf('the question', undefined, 41.9);
assertThat('value').isStrictlyEqualTo('value');
assertThat('4').isNotStrictlyEqualTo(4);
assertThat(['a', 'b', 'c']).contains('a', 'c');
assertThat(['x', 'y', 'z']).doesNotContain('f');
assertThat(['1', '2', '3']).containsExactly('3', '2', '1');
assertThat(['4', '5']).doesNotContainExactly('4');
assertThat('a string').hasLength(8);
assertThat([]).isEmpty();
assertThat('another string').isNotEmpty();

fail

Immediately fails the current test and prints the given message, if supplied.

Syntax

fail(opt_message);

Parameters

Parameter Type Description
opt_message string Optional error message text.

Example

fail('This test has failed.');

mock

The mock API allows you to override the behavior of Sandboxed APIs. The mock API is safe to use in template code, but it is operational only in test mode. Mocks are reset before each test is run.

Syntax

mock(apiName, returnValue);

Parameters

Parameter Type Description
apiName string The name of the API to mock; same string as passed to require()
returnValue any The value to return for the API or a function called in place of the API. If returnValue is a function, that function is called in place of the Sandboxed API; if returnValue is anything other than a function, that value is returned in place of the Sandboxed API.

Examples

mock('encodeUri', "https://endpoint.example.com/?account=12345");
mock('sendPixel', function(url, onSuccess, onFailure) {
    onSuccess();
});

mockObject

The mockObject API lets you override the behavior of Sandboxed APIs that return an object. The API is safe to use in template code, but it is operational only in test mode. Mocks are reset before each test is run.

Syntax

mockObject(apiName, objectMock);

Parameters

Parameter Type Description
apiName string The name of the API to mock; same string as passed to require()
objectMock object The value to return for the API or a function called in place of the API. Must be an object.

Examples

const storage = {};
mockObject('localStorage', {
  setItem: (key, value) => {storage[key] = value;},
  getItem: (key) => storage[key],
});

runCode

Runs the code for the template, i.e. the content of the Code tab, in the current test environment with a given input data object.

Syntax

runCode(data)

Parameters

Parameter Type Description
data object Data object to be used in the test.

Return Value

Returns the value of a variable for variable templates; returns undefined for all other template types.

Example

runCode({field1: 123, field2: 'value'});