GTM: Access dataLayer Variables from Custom HTML Tags

In general there are several possibilities on how to access the Google Tag Manager data layer variables from custom HTML tags. Depending on what exactly you want to achieve, one of methods described in the following section might be more or less suitable.

GTM variables

In most cases this should be the “cleanest” and most simple solution. Just setting up a corresponding data layer type variable in the GTM Interface. Afterwards this variable can be referenced in the custom HTML tag by using the syntax {{variableName}}.

Data layer object with index

This data layer access method offers the possibility to access the values of a certain data layer update step. In order to use it, you just need to reference the data layer object with the corresponding index of the update step. In example if you want to access the initial data layer setup, defined in the page source code before the GTM container code, you could use the syntax dataLayer[0]. To access the a certain variable of this initial data layer definition, you can use the syntax dataLayer[0]['variableName'].

Data layer object get and set functions

Another possibility to access and manipulate current data layer values, even without a dataLayer.push call, is provided by the get and set function of the tag manager data layer object. The get and set functions are not defined for the global data layer object but only for the tag manager data layer object, which can be accessed by using the following syntax:

Pushing a JavaScript Function into data layer

Finally theres one other possibility which can be used to manipulate a data layer variable (in example inside a custom HTML tag). With this method, a JavaScript function is pushed to the data layer, which is then automatically executed in the corresponding context, providing access to the data layer get and set functions.

Leave a Reply

Your email address will not be published. Required fields are marked *