Google Tag Manager Data Layer Tutorial with Examples

If you have used Google Tag Manager (GTM) for longer than a few days, you already know that GTM does require a good knowledge of HTML, DOM, and JavaScript as a prerequisite.

If you have implemented ecommerce tracking via GTM or enhanced ecommerce tracking via GTM, you will know that you need the help of a web developer to create the data layer for you.

When you have used GTM for long enough, you know that the real power of GTM lies in the usage of variables, especially custom variables that require coding knowledge.

GTM is a really powerful tool and understanding the data layer is the key to getting the most out of Google Tag Manager.

If you are brand new to GTM, then read this article first: Beginners Guide to Google Tag Manager

The three layers in programming

In the context of programming there are three different types of layers (also called ‘logic’):

  1. Presentation layer
  2. Business layer
  3. Data layer

#1 Presentation layer (or presentation logic)

The presentation layer corresponds to the user interface. It is used to manage interaction with the users.

The presentation layer is made up of one or more scripting languages. The three scripting languages which are most commonly used for creating a presentation layer are HTML, CSS, and JavaScript.

  • HTML (or HyperText Markup Language) is used to develop text content of a presentation layer.
  • CSS (or Cascading Stylesheet) is used to control the layout and formatting of the text developed through HTML.
  • JavaScript is used to control the behavior of HTML and CSS elements, users and web browsers.

When you interact with a web page, you are interacting with the presentation layer.

#2 Business layer (or business logic)

The business layer corresponds to business rules and workflows that determine how data can be created, stored and changed. The business layer sits between the presentation layer and the data layer.

#3 Data layer (or data logic)

The data layer corresponds to the data structure and database. The data layer should contain all the data you want to send to various analytics and/or marketing tags.

The data layer is the source of a vast amount of customer interaction data, website-related data and campaign data, which fuels the tag management system. This data powers vendor solutions like Google Analytics and can be a point of departure for data-driven initiatives.

Why do you need a data layer?

A data layer provides a safer and reliable way to pull data from the presentation layer and send it to the container tag (aka GTM).

You can directly pull data from the presentation layer by traversing the HTML DOM (structure of HTML) using JavaScript and then send the data to the container tag. When you pull data directly from the presentation layer and push it into your analytics and marketing tags (via GTM), you create an unreliable tracking setup.

The problem with this approach is that the presentation layer can change any day, any time without your knowledge, as commercial websites update all the time and as a result, any tag can stop working any day, any time without any prior notice.

To fix the problem, we create and use data layers, which stores all the information we want to collect about a web page:

Once you have set up a data layer, the container tag should be used, to pull data from the data layer of a page instead of its HTML DOM (the presentation layer).

So no matter what happens to HTML DOM, the data layer will remain the same and your tags will continue to work (unless of course, someone/ something breaks the data layer itself).

When can you use DOM scraping instead of data layers?

Each tag management solution (TMS) provider, implement the data layer in a slightly different way. So most likely, you won’t be able to use the same data layer with every TMS (if you use more than one TMS).

Data layers should be hard-coded on a website by your developer or IT team.  So as long as you are using data layers, you may need to depend upon IT for its updates and maintenance.

DOM scraping is a technique used to pull data directly from the HTML elements (buttons, links, forms, etc) of a web page by using JavaScript and the knowledge of HTML DOM.

Almost all TMS vendors provide the functionality of scraping the HTML DOM. DOM scraping comes handy when it is not possible to implement the required data layers in a reasonable amount of time, in order to set up certain tracking.

Through DOM scraping you can implement TMS solutions faster, as there is little to no dependence on IT and you have more control over the implementation.

However, the TMS solution implemented through DOM scraping is not a stable solution, as changes in the HTML DOM (like a change in the ID of an HTML element) can quickly break the TMS solution.

So TMS solution deployment through DOM scraping is more of a quick fix when you lack development resources or time. It is not something, you can/should rely upon for a long period of time and/or where a lot of money is at stake (like setting up tracking for an airline website).

What information should you store in a data layer?

If you want to avoid the hassle of modifying data layers every time you deploy a new GTM solution then you should aim to hard-code one universal data layer on each web page of your website. Each universal data layer should include all the key attributes of the web page, on which it is embedded.

Your data layer should include all the key information your marketing and analytics tags currently need.  It should also include all the key information you may need in the near future, for additional tracking.

This information could be:

#1 Page attributes

  • page title
  • page URL
  • page category, etc

#2 Product(s)’ attributes – attributes of a product(s) listed on a web page like:

  • product name
  • product id
  • product price
  • product category
  • product image URL
  • product variant (color, size, dimension) selected
  • product quantity selected
  • product views
  • product clicks (clicks on a product listing on a category page)
  • product availability (available, out of stock)
  • product coupon
  • product coupon used

#3 Users’ attributes

  • User ID (login ID)
  • Client ID
  • User type (logged-in user, logged-out user, member, non-member, customer, non-customer, repeat customer, high-value repeat customer, etc)
  • User’s browsing behavior
  • User’s preferences
  • User’s purchase history
  • Users’ interactions (clicking a button, submitting forms, signups, purchase, watching videos, etc)
  • Users’ web browser
  • Users’ operating system
  • Users’ device (mobile, desktop, tablet)

Any information that might be useful for additional tracking, either today or in the near future, should be included in the universal data layer.

What is a data layer in the context of Google Tag Manager?

A data layer is a JavaScript array of a single object which is used:

  • To store all the key attributes of a web page like page title, page URL, page category, etc.
  • To store all the key information your marketing and analytics tags currently need like user ID, client ID, user’s preferences, users’ purchase history, product ID, product price, etc.
  • To store all the key information you may need in the near future, for additional tracking.
  • To send information from a website to the GTM container tag.

In order to understand the concept of a data layer, you would first need to understand JavaScript arrays and objects.

Introduction to arrays and variables

An array is a special variable that can store multiple elements, of the same or different data types, at a time.

A variable is a location in the computer memory which is used for storing data. A variable can store different data at different times.

For example, if ‘a’ is the name of a variable, then ‘a’ can be used to store a value like ’10’ and then at a different point in time, can be used to store another value like ’20’.

a = 10;
a = 20;

However, a variable can store only one value at a time. If you want a variable to store more than one value at a time, then you need to use a special variable called an array.

An array is made up of one or more elements. These elements can be strings (like ‘hello’), numeric values (like 10), undefined values, Boolean values (like true, false), other arrays or objects.

Creating an array variable via the array function

An array can be created, by either using the array function or array literal notation [].

For example, here is how the empty array created through array function will look like in JavaScript:

var a=new Array();

Here ‘a’ is the name of the array and ‘var’ is a command which is used to create a variable in JavaScript. You can give any name to your array. For example:

var myArray = new Array();

Creating an array variable via array literal notation

The array literal notation method is preferred, for creating an array.

For example:

var a= [];

//Or

a= [];

Here a =[] is an empty array.

Following is an example of an array variable which contains one element of type number:

a = [10];

Following is an example of an array variable which contains two elements of type number:

a = [10, 20];

Following is an example of an array variable which contains one element of type string:

a = [“Hello”];

Following is an example of an array variable which contains three elements of type String:

a=[“hi”,”bye”,”goodbye”];

Following is an example of an array variable which contains one element of type number and one element of type string:

a = [100, “Hello”];

Get the E-Book (50 Pages)

Get the E-Book (100+ Pages)

Arrays which contains elements of different data types

An array variable can be used to store elements of different data types.

For example, you can create an array which contains both string and number values:

a1=["hi","bye","goodbye", 10, 20, 56];

Here, the array variable named ‘a1’ is made up of six elements. Out of these six elements, the first three elements are of type string and the last three elements are of type ‘number’.

You can also create an array, like the one below:

a2=["hi",10,"bye",20, 56,"good bye"];

Here, the array variable named ‘a2’ is made up of six elements. Out of these six elements, three elements are of type string and the remaining three elements are of type ‘number’.

Note: Even when both a1 and a2 contain the same elements, they are still different array variables because the order of the elements is different.

Different types of array variables

Following are the different types of array variables:

  • Array of Strings
  • Array of numbers
  • Array of undefined values
  • Array of Boolean values
  • Array of objects
  • Array of array

Introduction to an array of Strings

Following is an example of an array of Strings:

a=["hi","bye","goodbye"];

Here the array variable named ‘a’ has got three elements named: ‘hi’, ‘bye’ and ‘goodbye’.

All of these three elements are of type String as they are String values. We call such arrays an array of Strings.

Introduction to an array of numbers

Following is an example of an array of numbers:

a=[10,24,56];

Here, all of these three elements have got numeric values. We call such arrays an array of numbers.

Array of undefined values

Following is an example of an array of undefined values:

a=[,,,]; // array of undefined values.

We use a comma in place of value to create an undefined value.

Array of Boolean values

Following is an example of an array of Boolean values:

a=[true,false]; // array of Boolean values

Array of array (or multi-dimensional array)

A multi-dimensional array is an array that contains one or more arrays.

For example:

a=[[“Clasicos”,57],[“Zapatos”,456]];

Here the array named ‘a’ contains the following two elements of type ‘array’:

[“Clasicos”,57] [“Zapatos”,456]

Accessing the elements of an array

You can access an array element by referring to its index number. An Array index number starts with zero.

For example, consider the following array:

a=[10,24,56];

Here,

a[0] refers to the first element of the array i.e. 10

a[1] refers to the second element of the array i.e. 24

a[2] refers to the third element of the array i.e. 56

Introduction to objects

Just like an array, an object is also a special variable that can store multiple elements, of the same or different data types, at a time. However, unlike an array, an object’s element/property is in the format name:value.

Here, ‘name’ is the property name and ‘value’ is the property value.

Creating an object variable via object literal notation

The object literal notation is the preferred method for creating an object.

For example:

var a= {};

//Or

a= {};

Here a ={} is an empty object.

Note: You can give any name to the JavaScript object.

Following is an example of an object variable which contains one element:

User = {“firstName”:”John”};

Following is an example of an object which contains two elements:

User = {“firstName”:”John”, “lastName”:”Marshall”};

Following is an example of an object which contains four elements:

User = {“firstName”:”John”, “lastName”:”Marshall”, “age”:85, “eyeColor”:”blue”};

Following is the syntax to create a JavaScript object:

<object-name>={“property-name1”:property-value1, “property-name2″:property-value2, …..”property-nameN”:property-valueN};

Here property-name can be any string or identifier.

An identifier is a reserved word, which carries a special meaning and cannot be used as a variable name. For example ‘event’ is an identifier.

A property’s value can be a:

  1. String
  2. numeric value
  3. undefined value
  4. Boolean value
  5. array
  6. multi-dimensional array
  7. object
  8. an array of objects.

Improving the readability of an object

The following example code creates an object called “user” and adds four properties to it:

user={“firstName”:”John”, “lastName”:”Marshall”, “age”:85, “eyeColor”:”blue”};

Since white spaces and line breaks are not important in JavaScript. So to improve readability you can write the same ‘user’ object as:

 user={

"firstName":"John",

"lastName":"Marshall",

"age":45,

"eyeColor":"blue"

};

Other examples of objects

a = {"color":"Caf\u00e9"};

Here ‘color‘ is the name of the property of the object ‘a’ and ‘Caf\u00e9‘ is the value of the ‘color’ property which is a string.

a = {"price":164900.00};

Here ‘price‘ is the name of the property of the object ‘a’ and ‘164900.00‘ is the value of the ‘price’ property which is a numerical value.

a = {"color":"Caf\u00e9", "price":164900.00};

Here the object ‘a’ has got two properties ‘color’ and ‘price’.

Similarly, we can define an object with multiple properties:

a = {

"color":"Caf\u00e9", // the value is of type 'string'

"price":164900.00, // the value is of type 'numeric'

"sizeList":"", // the value is of type 'undefined'

"visitorsHasOrders":true, // the value is of type 'boolean'

"data":[45,67,89,20], // the value is of type 'array'

"shoppingCart":[["Clasicos",57],["Zapatos",456]], // the value is of type 'multi dimensional array'

"pageAttributes":{"page":"product"}, // the value is of type 'object'

"pageCategory":[   // the value is of type 'array of objects'

{"id":"20","name":"Zapatos"},

{"id":"53","name":"Masculino"},

{"id":"57","name":"Clasicos"},

{"id":"138","name":"Deportes"},

{"id":"139","name":"Masculino"}

{"id":"201","name":"Zapatos"},

{"id":"1244","name":"Mocasines"},

{"id":"1340","name":"Apaches"}

]

};

Accessing the elements of an object

You can access an object element/property by referring to its property name.

There are two methods to access object properties:

objectName.propertyName

or

objectName[“propertyName”]

For example, consider the following object:

User = {“firstName”:”John”, “lastName”:”Marshall”};

Here,

User.firstName refers to the first element of the object.

User.lastName refers to the second element of the object.

Similarly,

User[“firstName”] refers to the first element of the object.

User [“lastName”] refers to the second element of the object.

Difference between arrays and objects

Following is an example of an array that has the following three properties/elements: “Amit”, “Sinha” and 35:

a = [“Amit”, “Sinha”, 35];

Since we use numbers to access array elements, we can access the first property of the array ‘a’ by the notation:

a[0];

We can re-write the array ‘a’ as the following object:

b = {“FirstName”: “Amit”, “LastName”:”Sinha”, “Age”: 35};

Here ‘b’ is an object that has the following three properties/elements:

  1. “FirstName”: “Amit”
  2. “LastName”:”Sinha”
  3. “Age”: 35

Since we use property names to access object elements, we can access the first property of the object ‘b’ by the notation:

b.FirstName;

So while both array and objects are special variables that can store multiple elements (of the same or different data types) they store data in a different format and are accessed differently.

In JavaScript, arrays use numbered indexes whereas objects use named indexes.

Array of objects

An array variable can also be used to store one or more objects.

Following is an example of an array variable which contains only one object:

a=[{"id":"20","name":"Zapatos"}];

Here the object is: {“id”:”20″,”name”:”Zapatos”}

Following is an example of an array variable which contains two objects:

a=[{"id":"20","name":"Zapatos"},{"id":"53","name":"Masculino"}];

Here the objects are:

  • {“id”:”20″,”name”:”Zapatos”}
  • {“id”:”53″,”name”:”Masculino”}

White spaces and line breaks are not important in JavaScript. So to improve readability you can write the array named ‘a’ as:

a=[

{"id":"20","name":"Zapatos"},

{"id":"53","name":"Masculino"},

];

Following is an example of an array variable which contains multiple elements of type ‘object’:

a=[

{"id":"20","name":"Zapatos"},

{"id":"53","name":"Masculino"},

{"id":"57","name":"Clasicos"},

{"id":"138","name":"Deportes"},

{"id":"139","name":"Masculino"}

{"id":"201","name":"Zapatos"},

{"id":"1244","name":"Mocasines"},

{"id":"1340","name":"Apaches"}

];

Array of all available data types

You can also create an array which contains elements of all available data types:

a=["size", 10, true,,["Clasicos",57],{"id":"20","name":"Zapatos"}];

Here,

“size” is an array element of type String.

10 is an array element of type number.

true is an array element of type Boolean.

,, (empty value) is an array element of type undefined.

[“Clasicos”,57] is an array element of type array.

{“id”:”20″,”name”:”Zapatos”} is an array element of type object.

White spaces and line breaks are not important in JavaScript, so to improve readability you can write the same ‘a’ array as:

a=[

"size",

10,

true,

["Clasicos",57],

{"id":"20","name":"Zapatos"}

];

Introduction to variable types in Google Tag Manager

Google Tag Manager supports different types of variables which can be pushed into dataLayer. These variables can be broadly classified into two categories: built-in variables and user-defined variables.

#1.Built-in variables

These are predefined and configured variable in GTM. They are ready to use variables.

A brand new GTM container is not enabled with built-in variables. In order to enable and use the various built-in variables follow the steps below:

Step-1: Login to your GTM account.

Step-2: Click on the ‘Variables’ link in the left-hand side navigation menu.

Step-3: Click on the ‘Configure’ button:

 

Step-4: Click on the checkbox next to each variable name:

Once you enable the variables they will automatically be available in the data layer.

Following are the various built-in variables available in GTM:

Pages

Page URL: Provides/returns the full URL of the current page. For e.g. “www.abc.com/products/newsunglasses”

Page Hostname: Provides the hostname portion of the current page. For e.g if the current page is
“www.abc.com/products/newsunglasses” then the ‘Page Hostname’ variable would return “www.abc.com”

Page Path: Provides the path portion of the current page. For e.g if the current page is
“www.abc.com/products/newsunglasses” then the ‘Page Path’ variable would return “/products/newsunglasses”

Referrer: Provides the full URL of the page which brought a user to the current page.

Utilities

Event: Gives details of current data layer events like DOM Ready, Page Load, Window Load, Click, etc

Environment Name: Returns the user-provided name of the environment currently being previewed.

Container ID: Provides the GTM container’s public ID. Example value: GTM-XXX12

Container Version: Provides the current version number of the container, as a String.

Random Number: Returns a random number value.

HTML ID: Returns the identifier of the custom HTML tag.

Errors

Error Message: This variable returns a string value that contains the error message displayed to a user.

Error URL: This variable returns a string value that contains the URL where the error occurred.

Error Line: This variable returns a numerical value or number of the line in the file where the error occurred.

Debug Mode: This variable returns true if the GTM container is currently in preview mode.

Clicks

Click Element: This variable returns the HTML element that was clicked.

Click Classes: This variable returns the value (of type String) of the ‘class’ attribute of the HTML element that was clicked.

Click ID: This variable returns the value (of type String) of the ‘ID’ attribute of the HTML element that was clicked.

Click Target: This variable returns the value (of type String) of the ‘target’ attribute of the HTML element that was clicked.

Click URL: This variable returns the String contained in the ‘href’ or ‘action’ attribute of the HTML element that was clicked.

Click Text: This variable returns the value of text clicked by a user.

Forms

Form Element: This variable returns the form element (like Dropdown, Radio Button, Text Box) that was clicked.

Form Classes: This variable returns the String contained in the ‘class’ attribute of the form element that was clicked.

Form ID: This variable returns the String contained in the ‘ID’ attribute of the form element that was clicked.

Form Target: This variable returns the String contained in the ‘target’ attribute of the form element that was clicked.

Form URL: This variable returns the string contained in the ‘href’ or ‘action’ attribute of the form element that was clicked.

Form Text: This variable returns the text provided by a user in a form field

History

These variables are used to track virtual page views when there is no change in URL.

New History Fragment: This variable returns the string value of the fragment (aka hash) portion of the page’s URL after the history event.

Old History Fragment: This variable returns the string value of the fragment (aka hash) portion of the page’s URL before the history event.

New History State: This variable returns the value of the state object that the page pushed onto the history to cause the history event.

Old History State: This variable returns the value of the state object that was active before the history event took place.

History Source: This variable returns a string which refers to the event that initiated the history change.

Videos

Video Provider: This variable returns the name of the video provider (i.e. YouTube).

Video Status: This variable returns the current state of video like play, pause, stop, buffering etc.

Video URL: This variable returns the URL of the embedded video e.g. ‘https://www.youtube.com/watch?v=optimisesmart’.

Video Title: This variable returns the title of the embedded video.

Video Duration: This variable returns the total duration of a video in seconds.

Video Current Time: This variable returns an integer that represents the time in seconds where a user currently is.

Video Percent: This variable returns an integer that represents the percentage of video watched by a user.

Video Visible: This variable returns true or false, depending upon if the video was visible in the browser viewport.

Scrolling

Scroll Depth Threshold: This variable returns a numeric value from 0 to 100 specified as scrolling threshold.

Scroll Depth Units: This variable returns either ‘pixels’ or ‘percent’ depending upon which threshold type a trigger is tracking.

Scroll Direction: This variable returns the direction of Scroll with string value like “Vertical” or “Horizontal”

Visibility

Percent Visible: This variable returns a numeric value (0-100) that indicates how much of the tracked element has been in the browser viewport when the trigger fires.

On-Screen Duration: This variable returns a numeric value that indicates how many milliseconds the tracked element has been in the browser viewport when the trigger fires.

#2. User-defined variables

User-defined variables are custom created variables to suit a specific set of requirements which is not covered in built-in variables. You can access the user-defined variables in the variables menu.

In order to create a new user-defined variable, follow below steps

Step-1: click on the ‘Variables ‘tab and click on ‘New’ under ‘User-Defined Variables’.

Step-2: A new window will pop up, like below. Give it a proper name and click on ‘Variable configuration’.

Step-3: In Variable Configuration you will several types of user-defined variables as below (Click on the type of variable you want to create).

The following list will give you an idea of supported user-defined variables

Navigation:

  • HTTP Referrer: This variable returns “Previous Page URL” or Referrer (Type of value: String)
  • URL: Current URL: This variable returns current URL of page loaded on the website (Type of Value: String)

Page variables:

  • 1st party cookie: This variable returns the cookie value set in with specific domain name (Type of value could be String or number, based on business requirement).
  • Custom JavaScript: This variable is a custom JavaScript function which is used to pass website parameters in variable.
  • Data layer: The data layer variable corresponds to array of values that are collected across your site and the visitor interactions and events that are tracked.

Page elements:

  • Auto-event variable: this variable identifies auto events like click, form submission, element visibility on the website and returns parameters associated with the event.
  • DOM element: This variable returns the value of the text of the DOM (Document Object Model) element or the value of the specified DOM element attribute on the page.
  • Element visibility: This variable returns the value to True for a specified object when it’s visible, like a pop-up. It also returns the percentage of the element’s visibility, like 50%.

Utilities:

  • Constant: This variable returns a constant number.
  • Custom event: This variable returns custom event sent to dataLayer.
  • Environment name: Returns the user-provided name of the environment currently being previewed.
  • Google Analytics settings: This variable returns the Google Analytics Account ID.
  • Lookup table: This variable based on the certain conditions evaluates the condition first and then accordingly sets a value of a specific variable.
  • Random number: This variable returns a random number between 0 and 2147483647.
  • RegEx table: this variable is an advanced version of lookup table which runs on regular expressions.

Google Tag Manager uses the array variable name called ‘dataLayer’

So if you want to create an empty data layer array, it would look like the one below:

dataLayer=[];

Since this line of code is a JavaScript statement, you need to enclose it within the <script> and </script> tags, so that you can embed the code into your HTML document.

So the final setup will look like the one below:

<script>

dataLayer=[];

</script>

Congratulations, you just created your first data layer.

Note: A data layer is also known as dataLayer queue, dataLayer object, and data collection layer.

Data layer is an array of a single object

In the context of Google Tag Manager, a data layer is usually an array of a single object:

dataLayer=[{}];

Since this line of code is a JavaScript statement, you need to enclose it within the <script> and </script> tags, so that you can embed the code into your HTML document.

So the final setup will look like the one below:

<script>

dataLayer=[{}];

</script>

Following is an example of a data layer which contains one element:

dataLayer = [{ ‘pageCategory’: ‘Statistics’ }];

Following is an example of a data layer which contains two elements:

dataLayer = [{ ‘pageCategory’: ‘Statistics’, ‘visitorType’: ‘high-value’ }];

Following is an example of a data layer which contains more than two elements:

dataLayer=[ {

"color":"Caf\u00e9",

"price":164900.00,

"sizeList":"",

"visitorsHasOrders":true,

"data":[45,67,89,20],

"shoppingCart":[["Clasicos",57],["Zapatos",456]],

"pageAttributes":{"page":"product"},

"pageCategory":[

{"id":"20","name":"Zapatos"},

{"id":"53","name":"Masculino"},

{"id":"57","name":"Clasicos"},

{"id":"138","name":"Deportes"},

{"id":"139","name":"Masculino"}

{"id":"201","name":"Zapatos"},

{"id":"1244","name":"Mocasines"},

{"id":"1340","name":"Apaches"}

]

}];

Congratulations, you have just created your first complex data layer.

Get the E-Book (50 Pages)

Get the E-Book (62 Pages)

Quick recap

Remember:

a=[]; // creates an array

a={}; // creates an object

a=[{}]; // creates an array of a single object

dataLayer in GTM is an array of a single object.

So, 

dataLayer = [{…}];

What are data layer variables?

These are the variables used in the data layer.

It is in the format: ‘variable_name’: ‘variable_value’.

Following is an example of a data layer which contains no variable:

<script>

dataLayer = [{}];

</script>

Following is an example of a data layer which contains one variable:

<script>

dataLayer = [{'pageCategory': 'Statistics'}];

</script>

Following is an example of a data layer which contains two variables:

<script>

dataLayer = [{'pageCategory': 'Statistics', 'visitorType': 'high-value'}];

</script>

Since white spaces and line breaks are not important in JavaScript, so to improve readability you can re-write the data layer as:

<script>

dataLayer = [{

'pageCategory': 'Statistics',

'visitorType': 'high-value'

}];

</script>

Following is an example of a data layer which contains three variables:

<script>

dataLayer = [{

'pageCategory': 'Statistics',

'visitorType': 'high-value',

’event’:’customizeCart’

}];

</script>

Here, PageCategory, visitorType and event are the names of the data layer variables.

The value of PageCategory is Statistics’.

The value of visitorType is High Value’.

The value of event is customizeCart

Note: Data layer variables are also known as data layer messages.

How you can initialize a data layer?

By setting up variables in your data layer.

Initializing a data layer with one variable:

<script>

dataLayer = [{'pageCategory': 'Statistics'}];

</script>

Initializing a data layer with two variables:

<script>

dataLayer = [{

'pageCategory': 'Statistics',

'visitorType': 'high-value'

}];

</script>

Initializing a data layer with three variables:

<script>

dataLayer = [{

'pageCategory': 'Statistics',

'visitorType': 'high-value',

’event’:’customizeCart’

}];

</script>

Appending/passing messages onto the data layer queue => Adding data layer variables to the data layer.

Updating data layer => adding/updating/removing data layer variables.

Pushing information into the data layer => adding data layer variables to the data layer.

How is information pushed into a data layer?

There are two methods that can be used to push information into a data layer:

#1 By hard-coding the data layer variables in the data layer, preferably above the container tag.

#2 By dynamically adding objects to your data layer through the ‘push’ method of dataLayer object.

Use the first method, if you want to push information into a data layer on page load. For example, for ecommerce tracking or enhanced ecommerce tracking, we use the first method, as we want the ecommerce data to be available on page load.

Use the second method, if you want to push information into a data layer on any event other than the page load. For example, if you want to push information into the data layer on click on ‘Add to Cart’ button then use the second method.

The ‘push’ method of dataLayer object

Through the ‘push’ method of dataLayer object, you can dynamically add object(s) to your data layer. The pushed object can contain one or more data layer variables.

Following is the syntax of the ‘push’ method:

dataLayer.push({'variable_name': 'variable_value'});

For example, let us suppose the following data layer is hard-coded on a web page:

<script>

dataLayer = [{'pageCategory': 'Statistics'}];

</script>

Now, this data layer already contains one variable.

If you used the following push method:

<script>

dataLayer.push({'visitorType': 'high-value'});

</script>

The hard-coded data layer will now look like this:

<script>

dataLayer = [{'pageCategory': 'Statistics','visitorType': 'high-value'}];

</script>

You can also push/add multiple variables at once, into the data layer.

For example:

<script>

dataLayer.push({'pageCategory': 'Statistics','visitorType': 'high-value'});

</script>

Use ‘window.dataLayer.push()’

This is the same as the dataLayer.push() method but with an added advantage.

‘dataLayer’ is a global JavaScript array variable and can thus be accessed by any function that can also access the window object. The advantage of using the ‘window’ prefix is that you can avoid conflict with any local JavaScript array variable that uses the ‘dataLayer’ name.

So instead of using:

dataLayer.push({‘variable_name’: ‘variable_value’});

Use

window.dataLayer.push({‘variable_name’: ‘variable_value’});

Example-1:

<script>

window.dataLayer.push({‘visitorType’: ‘high-value’});

</script>

Example-2:

<script>

window.dataLayer.push({‘pageCategory’: ‘Statistics’,’visitorType’: ‘high-value’});

</script>

About ‘Scope’ in JavaScript

In JavaScript there are two types of scope: local scope and global scope. Scope determines the accessibility of JavaScript variables.

A variable declared within a JavaScript function is called local variable. A local variable has got a local scope and can only be accessed within the function where it is declared.

A variable declared outside any function is called global variable. A global variable has got a global scope and can be accessed by any function.

Note: In JavaScript, objects and functions are also called as variables.

Multiple initializations of a data layer leads to overwriting of the data layer

Let us suppose the following data layer is hardcoded in the head section (<head>….</head> of a web page

<script>

dataLayer = [{‘pageCategory’: ‘Statistics’}];

</script>

Let us suppose, you later, hardcoded second data layer somewhere in the body section (<body>….</body>) of the web page:

<script>

dataLayer = [{‘visitorType’: ‘high-value’}];

</script>

Now what will happen on page load, is that only the data from the second data layer will be available to the GTM container tag. The second initialization of the data layer will overwrite the first one. So if you want to access the ‘pageCategory’ data layer variable from within GTM, you won’t be able to. Because on page load, the data layer will look like this:

<script>

dataLayer = [{‘visitorType’: ‘high-value’}];

</script>

Instead of:

<script>

dataLayer = [{

‘pageCategory’: ‘Statistics’,

‘visitorType’: ‘high-value’

}];

</script>

In order to avoid this issue, do not initialize a data layer more than once on the same webpage. If you want to push new information to the existing data layer then use the ‘window.push()’ method. For example,

<script>

dataLayer = [{‘pageCategory’: ‘Statistics’}];

</script>

.

.

<script>

window.dataLayer.push({‘visitorType’: ‘high-value’});

</script>

Now the final data layer after the push will look like the one below:

<script>

dataLayer = [{

‘pageCategory’: ‘Statistics’,

‘visitorType’: ‘high-value’

}];

</script>

Push information into a data layer only if the ‘dataLayer’ variable has already been declared

In order to avoid multiple initializations of a data layer and consequently overwriting the data layer with new information, always check whether the dataLayer variable has already been declared. If the dataLayer variable has already been declared, only then proceed to push new information. You can achieve this objective by using the following code:

<script>

window.dataLayer = window.dataLayer;

window.dataLayer.push({‘variable_name’: ‘variable_value’});

</script>

If the dataLayer variable has not already been declared then assign a new empty array variable to it and only then proceed to push new information. You can achieve this objective by using the following code:

<script>

window.dataLayer = [];

window.dataLayer.push({‘variable_name’: ‘variable_value’});

</script>

In order to achieve both of the aforementioned objectives at the same time, combine the code like the one below:

<script>

window.dataLayer = window.dataLayer || [];

window.dataLayer.push({‘variable_name’: ‘variable_value’});

</script>

For example:

<script>

dataLayer = [{”pageCategory’: ‘Statistics’}];

</script>

.

.

<script>

window.dataLayer = window.dataLayer || [];

window.dataLayer.push({‘visitorType’: ‘high-value’});

</script>

Now, the final data layer will look like the one below:

<script>

dataLayer = [{

‘pageCategory’: ‘Statistics’,

‘visitorType’: ‘high-value’

}];

</script>

Overwriting the value of an existing data layer variable

By pushing a variable of the same name as an existing variable, but with a new value to the data layer. Let us suppose this is your existing data layer:

<script>
dataLayer = [{'pageCategory': 'Statistics','visitorType': 'high-value'}];
</script>

Now if you used the push method, like the one below:

<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({'pageCategory': 'Maths'});
</script>

The value of pageCategory data layer variable would be overwritten and now your data layer, would be like the one below:

<script>
dataLayer = [{'pageCategory': 'Maths','visitorType': 'high-value'}];
</script>

Data layer for ecommerce tracking (ecommerce data layer variables)

The data layer which contains ecommerce data layer variables is called the ecommerce data layer.

Following are the examples of ecommerce data layer variables which are recognized by GTM:

  • currencyCode
  • impressions
  • ecommerce
  • click
  • actionField
  • products
  • detail
  • add
  • remove
  • promoView
  • promotions
  • promoClick
  • checkout
  • checkout_option
  • purchase
  • refund 
  • id
  • affiliation
  • revenue, etc

Note: All the ecommerce data layer variables are reserved words (identifiers). They all carry a special meaning and therefore should not be used as a regular variable name in data layers while using GTM.

We use ecommerce data layers when we need to install ecommerce tracking or enhanced ecommerce tracking code on a website via GTM.

The ecommerce data layer pulls ecommerce data from your shopping cart (via a server-side script) and then sends the data to GTM.

Following is an example of ecommerce data layer:

<script>
// Send transaction data with a pageview if available
// when the page loads. Otherwise, use an event when the transaction
// data becomes available.
dataLayer.push({
  'ecommerce': {
    'purchase': {
      'actionField': {
        'id': 'T800',                         // Transaction ID. Required for purchases and refunds.
        'affiliation': 'OptimizeSmart',
        'revenue': '998.00',                     // Total transaction value (incl. tax and shipping)
        'tax':'199.6',
        'shipping': '1.9',
        'coupon': 'WINTER_SALE'
      },
      'products': [{                            // List of productFieldObjects.
        'name': '62 points GA Checklist',     // Name or ID is required.
        'id': '62',
        'price': '18.55',
        'brand': 'Optimize Smart',
        'category': 'eBook',
        'variant': 'Blue',
        'quantity': 1,
        'coupon': ''                            // Optional fields may be omitted or set to empty string.
       },
       {
        'name': '9 points social media checklist',
        'id': '9',
        'price': '19.75',
        'brand': 'Optimize Smart',
        'category': 'eBook',
        'variant': 'Green',
        'quantity': 1
       }]
    }
  }
});
</script>

Note: All the ecommerce data layer variables are highlighted in the code in bold text.

Ecommerce data layers contain server-side code

The ecommerce data layer that you saw earlier and the ecommerce data layers that you see in the Google help documentation are all example codes. You can’t just copy-paste them on your website and then expect the ecommerce tracking to work.

To make your ecommerce data layers to actually work and collect ecommerce data, you would need to add a server-side script (like PHP) to it.

For example, here is how a data layer with a server-side script, may look like:

datalayer with server side script

This is what a hardcoded ecommerce data layer actually looks like. You would need the help of a web developer to create ecommerce data layers.

What should be the format of the information you push into a data layer?

The information that you push into a data layer, from either the front-end or back-end, must be in the format, GTM can understand.

For example, if you try to push ecommerce data layer variables into a data layer which is not recognized/recommended by GTM, then your ecommerce tracking won’t work.

<script>

dataLayer = [{
.
.

'Transaction Id': '1234',

...

}]

}];

</script>

Here GTM won’t be able to recognize ‘Transaction Id’ as ecommerce data layer variable. The correct data layer snippet would be:

<script>

dataLayer = [{
.
.
'id': '1234',

...

}]

}];

</script>

Note: ‘id’ is an example of an identifier (reserved word). So it carries a special meaning and should not be used as a regular data layer variable name while using GTM.

Naming conventions for data layer variables

You should use a consistent naming convention for data layer variables. If you use different variable names that refers to the same variable on different pages, GTM may not be able to fire tags in all the desired locations. For example,

If you set up the page category for the ‘signup’ page by using the ‘pageCategory‘ data layer variable, then the page category for the product purchase page should also be set up by using the ‘pageCategory’ data layer variable and not by using data layer variables like ‘Pagecategory’ or ‘PageCategory’. That is because data layer variable names are case sensitive.

So the following set up won’t work the way, you think it should:

// signup page:

window.dataLayer.push({'pageCategory': 'members-signup'});

// Product purchase Page:

window.dataLayer.push({'PageCategory': 'product-purchase'});

But the following set up will work the way it should:
// signup page:

window.dataLayer.push({'pageCategory': 'members-signup'});

// Product purchase Page:

window.dataLayer.push({'pageCategory': 'product-purchase'});

Data layer variable names should be enclosed in quotes

window.dataLayer.push({pageCategory: 'members-signup'});    // Won't work

window.dataLayer.push({'pageCategory': 'members-signup'});    // works

The name ‘Data Layer’ itself is case sensitive

So, ‘dataLayer‘ is different from ‘datalayer‘, and using the latter won’t work.

For example:

window.datalayer.push({'pagecategory': 'members-signup'});    // Won't work

window.dataLayer.push({'pageCategory': 'members-signup'});    // works

What is an ‘event’ data layer variable?

It is a special data layer variable that is used with JavaScript event listeners. It is used to fire a tag when a user interacts with webpage elements such as form, button, links, etc.

The syntax for setting up an event:

window.dataLayer.push({'event': 'event_name'});

Here ‘event’ and ‘event name’ are strings.

For example, the following code update the data layer’s ‘event’ variable when a user clicks on a button:

<a href=”https://www.optimizesmart.com/download” name=”pdfDownload” onclick=”window.dataLayer.push({‘event’: ‘pdf-download’});” >PDF download</a>

Other examples of special data layer variables

  • hitType
  • nonInteraction
  • ecommerce etc

FAQs

Q. Can each web page have its own unique data layer?

A. Yes, and it should.

Q. Do you need to put the same set of variables in the data layer on every page?

A. No.

Q. When a data layer is updated in case of a tracked event?

A. When the tracked event occurs like: mouse click, form submission, page load, etc.

What are dynamic data layer variables?

Dynamic data layer variables are data layer variables which are pushed dynamically (during run time) to a data layer.

The syntax for setting up dynamic data layer variables

window.dataLayer.push({'variable_name': 'variable_value'});

For example, let us suppose the following data layer is hard-coded on a web page:

<script>

dataLayer = [{'pageCategory': 'Statistics'}];

</script>

If you used the following push method:

<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({'visitorType': 'high-value'});
</script>

The hard coded data layer will now look like the one below:

<script>
dataLayer = [{'pageCategory': 'Statistics','visitorType': 'high-value'}];
</script>

Here ‘pageCategory’ is a data layer variable whereas ‘visitorType’ is a dynamic data layer variable, as it has been pushed dynamically into the data layer during run time.

Note: Dynamic data layer variables are not hard-coded on a web page.

How you can rename a data layer (or data layer object)?

The default name of the data layer (or data layer object) is ‘dataLayer’.

By making a small change (highlighted below in bold text) in your GTM container code snippet you can rename your data layer:

<!-- Google Tag Manager -->

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':

new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],

j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=

'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);

})(window,document,'script','addYourNewDataLayerNameHere','GTM-XXXX');</script>

<!-- End Google Tag Manager -->

For example:

<body>

<script>

 SmartDataLayer = [{

'pageCategory': 'signup',

'visitorType': 'high-value'

}];

</script>

<!-- Google Tag Manager -->

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':

new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],

j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=

'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);

})(window,document,'script','SmartDataLayer','GTM-XXXX');</script>

<!-- End Google Tag Manager -->

<a href=”https://www.optimizesmart.com/download” name=”pdfDownload” onclick=”window.SmartDataLayer.push({‘event’: ‘pdf-download’});” >PDF download</a>

When do you need to rename your data layer?

You should rename your data layer when you are using multiple GTM container tags on the same web page and you don’t want each GTM container tag to use the same data layer.

For example:

<body>

<script>

dataLayer1 = [{

'pageCategory1': 'signup',

'visitorType1': 'high-value'

}];

</script>

<!-- Google Tag Manager  Container-1-->

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':

new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],

j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=

'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);

})(window,document,'script','dataLayer1','GTM-XXXX');</script>

<!-- End Google Tag Manager Container-2 -->

<!--===================================================================-->

<script>

dataLayer2 = [{

'pageCategory2': 'signup',

'visitorType2': 'high-value'

}];

</script>

<!-- Google Tag Manager Container -2 -->

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':

new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],

j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=

'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);

})(window,document,'script','dataLayer2','GTM-XXXX');</script>

<!-- End Google Tag Manager Container-2 -->

<!--=====================================================================-->

<script>

dataLayer3 = [{

'pageCategory3': 'signup',

'visitorType3': 'high-value'

}];

</script>

<!-- Google Tag Manager  Container-3 -->

<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXX"

height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':

new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],

j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=

'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);

})(window,document,'script','dataLayer3','GTM-XXXX');</script>

<!-- End Google Tag Manager Container-3 -->

<!--===================================================================-->

<a href=”https://www.optimizesmart.com/download1″ name=”pdfDownload1″ onclick=”window.dataLayer1.push({‘event’: ‘pdf-download1’});” >PDF download 1</a>

<a href=”https://www.optimizesmart.com/download2″ name=”pdfDownload2″ onclick=”window.dataLayer2.push({‘event’: ‘pdf-download2’});” >PDF download 2</a>

<a href=”https://www.optimizesmart.com/download3″ name=”pdfDownload3″ onclick=”window.dataLayer3.push({‘event’: ‘pdf-download3’});” >PDF download 3</a>

Note: By default, each GTM container tag uses a common data layer.

FAQ

Q. Do you need to be a web developer in order to use the data layer?

A. I am often asked this question. The answer is ‘no’, not for the very basic data layers. But you still need a basic knowledge of HTML, DOM, and JavaScript.

Q. When do you really need a web developer to write data layers for you?

A. When you have to create complex data layers, like the one which pulls ecommerce data from the back-end (server-side) and converts that data into a format, which GTM can understand.

What is a data layer snippet?

A data layer snippet is the data layer enclosed within <script> ….</script> tags.

Following is an example of a data layer snippet

<script>
dataLayer = [{'pageCategory': 'Statistics','visitorType': 'high-value'}];
</script>

What is a GTM container tag snippet?

It is the code that is used to create a new Google Tag Manager container tag. A container tag holds all the marketing/analytics tags, triggers, and variables for your website. When you are installing Google Tag Manager on your website, you are basically installing a container tag.

Following is an example of container tag snippet:

<!-- Google Tag Manager -->

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':

new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],

j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=

'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);

})(window,document,'script','dataLayer','GTM-XXXX');</script>

<!-- End Google Tag Manager -->

Note: The container tag snippet should be placed on each and every web page of your website.

Where you should place the data layer snippet?

The data layer snippet should be placed above your GTM container tag snippet in the head section (<head>….</head>) of a web page:

For example:

<head>
.
.
.

<script>

  dataLayer = [{'pageCategory': 'Statistics','visitorType': 'high-value'}];

</script>

<!-- Google Tag Manager -->

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':

new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],

j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=

'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);

})(window,document,'script','dataLayer','GTM-XXXX');</script>

<!-- End Google Tag Manager -->

</head>

<body>

<!-- Google Tag Manager -->

<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXX"

height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>


<!-- End Google Tag Manager -->

Why should the data layer snippet be placed above the GTM container snippet?

If you place the data layer snippet below the container tag snippet then the data layer variables may not be available to the container tag.

For example, the following set up may not work:

<!-- Google Tag Manager -->

...

<!-- End Google Tag Manager -->

<script>

  dataLayer = [{'pageCategory': 'Statistics','visitorType': 'high-value'}];

</script>

Here the data layer variables ‘pageCategory’ and ‘visitorType’ may not be available to the GTM container, as the data layer code has been placed after the container snippet.

FAQs

Q. When does Google Tag Manager function best?

A. When used alongside a data layer. You should know this by now!

Q. Is it mandatory to declare the data layer while using GTM?

A. No. Explicitly declaring a data layer is optional.

Q. Can you use GTM without explicitly implementing the data layer?

A. Yes. In that case, the GTM container code will automatically create its own empty data layer object for you.

Do you need a GTM container tag to implement a data layer?

No. You can create a JavaScript array that stores all the information you want to collect about a page and use it as a data layer. For example:

<script>

mydataLayer = [{

"pageCategory": "Statistics",

"visitorType": "high-value"

}];

</script>

FAQ

Q. How you can selectively fire tags on page load?

A. Through GTM triggers.

Q. What is the downside of not using the data layer?

A. You cannot use ‘events’ without data layer and above all your GTM implementation could be pretty shaky.

Q. How you can access values from a page without implementing the data layer?

A. By using GTM custom JavaScript variables.

How can you implement a data layer on a web page?

By adding following snippet of code above the container tag snippet in the head section <head>….</head> of your HTML document:

<script>

dataLayer = [];

</script>

For example, you might want to set data layer variables to indicate that the page is a ‘Maths’ page and that the visitor is a ‘high-value’ visitor. To do this, you initialize the data layer as follows:

<script>
dataLayer = [{'pageCategory': 'Maths','visitorType': 'high-value'}];
</script>

FAQ

Q. What is the scope of data layer variables?

A. Data layer variables are page specific. That means they exist, as long as a user remains on the same page.

Q. How you can declare data layer variables that are relevant across pages?

A. By using the same data layer variable name on multiple pages of your website.

A real-life example of a data layer being used on a website

<script type="text/javascript">

var dataLayer = [{

"color":"Caf\u00e9",

"deviceAgent":"Mozilla\/5.0 (Windows NT 6.3; WOW64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/35.0.1916.153 Safari\/537.36"

"deviceOs":"non-mobile",

"deviceTheme":"desktop",

"deviceType":"desktop",

"gender":"Masculino",

"googleRemarketingLabel":"",

"image":"http:\/\/static.dafyty.com.co\/p\/brahma-6338-0822-1-product.jpg",

"pageAttributes":{"page":"product"},

"pageBrand":[{"id":"2","name":"Brahma"}],

"pageCategory":[

{"id":"20","name":"Zapatos"},

{"id":"53","name":"Masculino"},

{"id":"57","name":"Clasicos"},

{"id":"138","name":"Deportes"},

{"id":"139","name":"Masculino"},

{"id":"201","name":"Zapatos"},

{"id":"1244","name":"Mocasines"},

{"id":"1340","name":"Apaches"}

],

"pageMainCategory":"id":"1340","name":"Apaches"},

"pageName":"product",

"pageProductDescription":"<i>Zapatos<\/i> <b>Brahma<\/b> cafe, elaborados en cuero con costuras visibles en la zona delantera la cual es redonda. Forro en cuero y suela en goma. Un calzado muy comodo que puedes combinar tanto con tus atuendos formales como informales.",

"pageProductName":"Zapatos Brahma Cafe",

"pageTitle":null,

"price":"164900.00",

"priceDiscount":"12%",

"season":"Todas las temporadas",

"seasonYear":"2012",

"shopAnalyticsAccount":"",

"shopName":"default",

"sizeList":"",

"sku":"BR002SH19DJS",

"specialPrice":"144900.00",

"urlPageProduct":"http:\/\/www.dafiti.com.co\/Zapatos-Brahma-Cafe-280.html",

}];

dataLayer = CookieTracking.changeGtm(dataLayer);

</script>

And here is how this data layer looks like in the Google Developer’s Tools console tab:

data layer example

If you look at this screenshot closely, you can see that all data layer variables are reported in alphabetical order in the developer’s tool console tab. That’s how you should write your data layer variables, in alphabetical order. This way the debugging of the data layer becomes easier.

Another thing worth noting is that the data layer above contains some dynamic data layer variables, near the end like VisitorsAge, VisitorsEmail, VisitorsGender, etc. These data layer variables weren’t hard-coded on the web page but were dynamically pushed into the data layer via the push method.

How to check the data layer in Google Chrome Console

You can see the data layer on any web page via the console tab of the Google Developer’s Tool.

To do that, follow the steps below:

Step-1: In Google Chrome, right-click on a web page (the page must have Google Tag Manager installed) and then select ‘Inspect’ from the drop-down menu:

This should open up the Google Developer’s  Tool window at the bottom of your screen:

Step-2: Click on the ‘Console’ tab at the top right of the tool window and then type ‘dataLayer’ at the command prompt:

You should now see a line of code just below the dataLayer:

Click on this line of code. You should now see all the data layer variables:

Click on a data layer variable to see more details about that variable:

 

gtm.js is a JavaScript library file used by the GTM container tag. If this library file doesn’t load then your GTM won’t work. Once the gtm.js library file is loaded, the container tag passes the event ‘gtm.js to the data layer.

gtm.dom is a DOM file used by the container tag. If this file doesn’t load then it means, DOM has not loaded. Once the DOM is loaded, the container tag passes the event ‘gtm.dom to the data layer.

gtm.load is a load file used by the container tag. If this file doesn’t load then it means the window and all its contents are not loaded. Once the window and all its contents are fully loaded, the container tag passes the event ‘gtm.load to the data layer.

These events are fired in the following sequence: gtm.js > gtm.dom > gtm.load

Every data layer gets these three events from the container tag. If your data layer doesn’t get any/all of these events then it means something has gone wrong with your tag manager implementation. It could either be a broken container tag or a broken data layer or both.

If you have a hard-coded data layer on a page then the developers’ tool window will show you at least four JavaScript objects. One JavaScript object would be your data layer and the other three will be the default JavaScript event objects:

javascript objects 2

How to check data layer in Google Tag Manager

To check or validate your data layer you can use Google Tag Manager preview tool.

Login to Tag Manager console. Click on ‘Preview’.

If preview mode is activated it will pop up an orange notification like below

Go to your website and refresh the page. Preview mode will be visible like below

On the right-hand side you will see the summary which gives the list of events happening on page. As we have seen till now, we can update data layer for any of the event dynamically by using dataLayer.push method.

Select any event for which you would like to see the data layer value and click on the ‘Data Layer’ Tab.

For the selected event, you can see now the dataLayer value after the Container loaded event fired.

You can see in the above image we can see two variables are initialised, which are

  • pageCategory: has value “Home”
  • visitorType: has value “high-value”

You can also verify the data layer variable in the variables tab for the same events which will give you the list of variables loaded when the events fired and value each variable is assigned. Just click on the variable for the corresponding event you want to check.

You can see in the below image that on Container Loaded we have few of our variables assigned with value. Event, Page Host name, Page Path, Page URL and Referrer are the predefined variables from Google Tag Manager.

While Page Category and Visitor Type are the data layer variables.

Note: Preview mode will not visible if you are using any extensions like Ghostery.

Frequently asked questions about data layers

What is a data layer?

A data layer is a JavaScript array which is used:
1) To store all the key attributes of a web page (like page title, page URL, page category, etc.)
2) To store all the key information your marketing and analytics tags currently need (like user ID, client ID, user's preferences, users' purchase history, product ID, product price, etc).
3) To store all the key information you may need in the near future, for additional tracking.
4) To send information from a website to GTM container tag.
Google tag manager uses the array variable name called 'dataLayer'.

Why do you need a data layer?

A data layer provide a safer and reliable way to pull data from presentation layer and send it to the container tag (aka GTM). You can directly pull data from the presentation layer by traversing the HTML DOM (structure of HTML) using JavaScript and then send the data to the container tag.

When you pull data directly from the presentation layer and push it into your analytics and marketing tags (via GTM), you create an unreliable tracking setup. The problem with this approach is that the presentation layer can change any day, any time without your knowledge, as commercial websites update all the time and as a result, any tag can stop working any day, any time without any prior notice.

To fix the problem, we create and use data layers, which stores all the information we want to collect about a web page. Once you set up a data layer, the container tag should be used, to pull data from the data layer of a page instead of its HTML DOM (the presentation layer). So no matter what happens to HTML DOM, the data layer will remain the same and your tags will continue to work (unless of course, someone/ something breaks the data layer itself).

How information is pushed into a data layer?

There are two methods that can be used to push information into a data layer:
#1 By hard coding the data layer variables in the data layer, preferably above the container tag.
#2 By dynamically adding objects to your data layer through the ‘push’ method of dataLayer object.

What is an array?

An array is a special variable which can store multiple elements of the same or different data types at a time. Variable is a location in the computer memory which is used for storing data. A variable can store different data at different times. However, a variable can store only one value at a time. If you want a variable to store more than one value at a time, then you need to use a special variable called 'array'.

An 'array' is made up of one or more elements. These elements can be: strings (like 'hello'), numeric values (like 10), undefined values, boolean values (like true, false), other arrays or objects.

How to create an Array Variable?

An array can be created, by either using the array function or array literal notation. The array literal notation is preferred, for creating arrays.

 

Another article you will find useful: Google Tag Manager Training Resources

Register for the FREE TRAINING...

"How to use Digital Analytics to generate floods of new Sales and Customers without spending years figuring everything out on your own."



Here’s what we’re going to cover in this training…

#1 Why digital analytics is the key to online business success.

​#2 The number 1 reason why most marketers are not able to scale their advertising and maximize sales.

#3 Why Google and Facebook ads don’t work for most businesses & how to make them work.

#4 ​Why you won’t get any competitive advantage in the marketplace just by knowing Google Analytics.

#5 The number 1 reason why conversion optimization is not working for your business.

#6 How to advertise on any marketing platform for FREE with an unlimited budget.

​#7 How to learn and master digital analytics and conversion optimization in record time.



   

My best selling books on Digital Analytics and Conversion Optimization

Maths and Stats for Web Analytics and Conversion Optimization
This expert guide will teach you how to leverage the knowledge of maths and statistics in order to accurately interpret data and take actions, which can quickly improve the bottom-line of your online business.

Master the Essentials of Email Marketing Analytics
This book focuses solely on the ‘analytics’ that power your email marketing optimization program and will help you dramatically reduce your cost per acquisition and increase marketing ROI by tracking the performance of the various KPIs and metrics used for email marketing.

Attribution Modelling in Google Analytics and Beyond
Attribution modelling is the process of determining the most effective marketing channels for investment. This book has been written to help you implement attribution modelling. It will teach you how to leverage the knowledge of attribution modelling in order to allocate marketing budget and understand buying behaviour.

Attribution Modelling in Google Ads and Facebook
This book has been written to help you implement attribution modelling in Google Ads (Google AdWords) and Facebook. It will teach you, how to leverage the knowledge of attribution modelling in order to understand the customer purchasing journey and determine the most effective marketing channels for investment.

Himanshu Sharma

Digital Marketing Consultant and Founder of Optimizesmart.com

Himanshu helps business owners and marketing professionals in generating more sales and ROI by fixing their website tracking issues, helping them understand their true customers' purchase journey and helping them determine the most effective marketing channels for investment.

He has over 12 years of experience in digital analytics and digital marketing.

He was nominated for the Digital Analytics Association's Awards for Excellence. The Digital Analytics Association is a world-renowned not-for-profit association that helps organisations overcome the challenges of data acquisition and application.

He is the author of four best-selling books on analytics and conversion optimization:

error: Alert: Content is protected !!