Custom template 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');

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 eventData 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, it's execution status, and its execution time.

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


encodeUri

Returns an encoded Uniform Resource Identifier (URI) by escaping special characters. Returns a string that represents the provided string encoded as a URI.

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.

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.


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 the returned integer.

Associated permissions

None.


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://www.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://www.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

Returns a number that represents the current time in milliseconds since the epoch (UTC timezone).

Syntax

getTimestamp()

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 will be returned.

Associated permissions

get_url


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


logToConsole

Logs arguments to the browser console.

Syntax

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

Parameters

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

Associated permissions

logging


makeInteger

Converts the given value to a number (integer).

Syntax

makeInteger(value)

Parameters

Parameter Type Description
value any type 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.


makeString

Returns the given value as a string.

Syntax

makeString(value)

Parameters

Parameter Type Description
value any type The value to convert.

Associated permissions

None.


queryPermission

Query the whitelisted 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 type 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 that can be called from your program.

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 is sent successfully.
onFailure function Called when the pixel fails.

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


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