The data layer | Google Tag Manager for the web | Google developer (2023)

The data layer is an object used by Google Tag Manager and gtag.js to pass information to tags. Events or variables can be passed through the data layer and triggers can be set based on variable values.

For example, if you trigger a remarketing tag when the value ofpurchase_totalis over $100, or based on specific events, for example when a button is clicked, your data layer can be configured to make this data available to your labels. The data layer object is structured as JSON. For example:

{ evento: "checkout_button", gtm: { uniqueEventId: 2, start: 1639524976560, scrollThreshold: 90, scrollUnits: "percent", scrollDirection: "vertical", disparadores: "1_27" }, value: "120"}

Google tags are designed to easily reference information added to the data layer in an organized and predictable way, rather than parsing variables, transaction information, page categories, and other signals scattered across the page. A data layer implementation filled with variables and associated values ​​will help ensure that the relevant data is available when your tags need it.

Installation

For Tag Manager web page installations, you must create a data layer. The highlighted code below shows where the data layer is set, before the TagManager is loaded.

<script>ventana.dataLayer = ventana.dataLayer || [];</script><!-- Administrador de etiquetas de Google --><script>(función(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='https://www.googletagmanager.com/gtm.js?id='+i+dl;f. parentNode.insertBefore(j,f);})(ventana,documento,'script','dataLayer','GTM-XXXXXX');</script><!-- Finalizar Google Tag Manager -->

In standard gtag.js implementations where the tag has been copied from within the product and added to a web page, code is provided to set the data layer. For custom Google tag implementations, add the data layer code to the beginning of your script, as shown in the highlighted example below:

<!-- Etiqueta de Google (gtag.js) --><script async src="https://www.googletagmanager.com/gtag/js?id=TAG_ID"></script><script>ventana.dataLayer = ventana.dataLayer || [];function gtag(){dataLayer.push(argumentos)}; gtag('js', nueva Fecha()); gtag('config', 'TAG_ID');</script>

How data layer information is processed

When a container is loaded, Tag Manager begins processing all queued data layer push messages. Tag Manager processes messages first in, first out: Each message is processed one at a time, in the order it was received. If the message is an event, all tags with trigger conditions that are met will be triggered before Tag Manager moves on to the next message.

And agtag()oCapaDeDatos.push()When a call is made via code in a page, custom template, or custom HTML tag, the associated message is queued and processed after all other pending messages are evaluated. This means that there is no guarantee that the updated data layer values ​​will be available for the next event. To handle these cases, you mustadd an event name to a messageas it is sent to the data layer, and then listen for the event name with acustom event trigger.

(Video) Data Layer in Google Tag Manager || GTM Data Layer Tutorial with examples

Using a data layer with event handlers

Odata layerobject uses aeventCommand to start sending events.

Google Tag and Tag Manager use a special data layer variable calledeventwhich are used by JavaScript event listeners to fire tags when a user interacts with elements on the site. For example, you might want to trigger a conversion tracking tag when a user clicks a checkout button. Events can be called whenever a user interacts with site elements such as links, buttons, scrolls, etc.

This functionality is achieved by callingCapaDeDatos.push()when an event occurs. The syntax for dispatching an event withCapaDeDatos.push()Is the next:

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

Wherename of the eventis a string that describes the event, such as'Connect-be',comprar, olook for.

To useCapaDeDatos.push()to send event data when an action occurs that you would like to measure. For example, to send an event when a user clicks a button, modify theon clickcontroller to callCapaDeDatos.push():

<button onclick="dataLayer.push({'event': 'login'});">Botão 1</button>

You can send variables from the data layer to the data layer dynamically to capture information such as values ​​entered or selected in a form, metadata associated with a video the visitor is playing, the color of a product (for example, a car) personalized by the visitor, the destination URLs of the links that were clicked, etc.

As with events, this functionality is accomplished by calling the methodto push()API to add or replace data layer variables in the data layer. The basic syntax for defining dynamic data layer variables is as follows:

(Video) Data Layer Explained With Practical Examples in Google Tag Manager

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

Where'variable name'is a string indicating the name of the data layer variable to define and'valor variable'is a string indicating the value of the data layer variable to set or replace.

For example, to set a data layer variable with a color preference when a visitor interacts with a product customization tool, you can send the following dynamic data layer variable:

dataLayer.push({'color': 'red'});

One push, multiple variables

You can send multiple variables and events at once:

dataLayer.push({ 'color': 'red', 'conversionValue': 50, 'event': 'custom'});

Persist data layer variables

To persist data layer variables in web pages, callCapaDeDatos.push()after the data layer has been instantiated on each page load and send the variables to the data layer. If you want these data layer variables to be available to the TagManager when the container loads, add aCapaDeDatos.push()call above Tag Manager container code as below.

<script>ventana.dataLayer = ventana.dataLayer || [];dataLayer.push({ 'event': 'Page Viewed', 'pagePath': 'https://www.googleanalytics.dev/pancakes', 'pageTitle': 'Pancake Event Log', 'visitorType': 'customer'});</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!='data layer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js ?id =' +i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-XXXXXX');</script><!-- Finish Google Tag Manager -->

Each variable declared in the data layer object will persist only as long as the visitor remains on the current page. Data layer variables that are relevant to pages (eg.visitor type) must be declared in the data layer on every page of your website. While you don't need to put the same set of variables in the data layer on every page, you should use a consistent naming convention. In other words: if you set the page category on the registration page using a variable calledcategory of page, your product and shopping pages must use thecategory of pagevariable too.

Troubleshooting

Here are some data layer troubleshooting tips:

do not replace theventana.dataLayervariable:When you use the data layer directly (for example,dataLayer = [{'element': 'value'}]), it will overwrite any existing value in thedata layer. Tag Manager installations should instantiate the data layer as high up in the source code as possible, above the containernippet or any Optimize pages that hide snippets, usingventana.dataLayer =ventana.dataLayer || [];. Afterdata layerhas been declared, usedataLayer.push({'element': 'value'})to add additional values ​​to it, and if those values ​​should be available to the Tag Manager when the page loads, then thisCapaDeDatos.push()The call must also be on top of the Tag Manager container code.

(Video) Introduction to Data Layer for Google Tag Manager (GTM)

Odata layerthe object name is case sensitive:If you try to send a variable or event without the proper case, the send will not work.

datalayer.push({'pageTitle': 'Home'}); // Bad (lowercase data layer) dataLayer.push({'pageTitle': 'Home'}); // Good (data layer in case of camel)

dataLayer.pushmust be called with valid JavaScript objects. All data layer variable names must be enclosed in quotes.

dataLayer.push({new-variable: 'value'}); // Bad - no quotes marksdataLayer.push({'new-variable': 'value'}); // Good - proper quotes

Keep variable names consistent across pages:If you use different variable names for the same concept on different pages, your tags may not fire consistently in all the places you want.

Spacious:

// Página de inicio:dataLayer.push({'visitorType': 'low-value'});// Check-out Page:dataLayer.push({'visitor_type': 'high-value'});

Name:

// Start page: dataLayer.push({'visitorType': 'low-value'});// Exit page: dataLayer.push({'visitorType': 'high-value'});

Rename the data layer

The default name of the data layer object launched by the Google Tag or Tag Manager isdata layer. If you prefer to use a different name for your data layer, edit the value of the data layer parameter in your Google Tag or Tag Manager container snippet with the name of your choice.

gtag.js

Add a query parameter called "l" to the URL to define the new name of the data layer, for examplel=meuNovoNumber. Update all instances ofdata layerin the Google tagnippet for the new name.

<!-- Etiqueta de Google (gtag.js) --><script async src="https://www.googletagmanager.com/gtag/js?id=TAG_ID&l=meuNovoNumber"></script><script> window.myNewName = window.myNewName || []; function gtag(){myNewName.push(arguments);} gtag('js', new Date()); gtag('config ', 'TAG_ID');</script>

tag manager

Replace the value of the data layer parameter (highlighted below) in your containernippet with the name of your choice.

<!-- Administrador de etiquetas de Google --><script>(función(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='https://www.googletagmanager.com/gtm.js?id='+i+dl;f. parentNode.insertBefore(j,f);})(janela,documento,'script','meuNovoNome','GTM-XXXXXX');</script><!-- Join Google Tag Manager -->
(Video) How to use a dataLayer variable to pull data from the GTM dataLayer [Quick Tip]

Once renamed, all references to its data layer (i.e., by declaring the data layer on top of the fragment or by sending events or dynamic variables from the data layer to the data layer with the.to push()command) should be adjusted to reflect the name of your custom data layer:

<script>meuNewName= window.DataLayer || [];meuNewName.push({'variable_name': 'variable_value'});</script>

Data Layer Custom Methods

If you send a function to the data layer, it will be called against this array in an abstract data model. This abstract data model can get and set values ​​for a key value store, and also provides a way to redefine the data layer.

define

OdefineThe function in the abstract data model allows you to define values ​​to retrieve via get.

window.dataLayer.push(function() { this.set('time', new Date());});

to take

Oto takeThe function in the abstract data model allows you to retrieve values ​​that have been defined.

(Video) Google Tag Manager - Overview of Data Layer

window.dataLayer.push(function() { const existingTime = this.get('time'); if (existingTime !== null) { // Change behavior based on whether this value exists or not... } else { / / ... }})

Resume

OResumeThe function in the abstract data model allows you to redefine the data in the data layer. This is most useful with a page that will stay open and the size of the data layer continues to grow over time. To reset the data layer, use the following code:

window.dataLayer.push(function() { this.reset();})

Videos

1. How to Transform the dataLayer with Google Tag Manager
(MeasureSchool)
2. What is DataLayer | Google Tag Manager Tutorial (Updated 2022 edition)
(DataVinci Analytics Agency)
3. Using the Google Tag Manager Data Layer with WordPress // Reporting on content and logged in users
(Loves Data)
4. Google Analytics Ecommerce Tracking with Google Tag Manager (Part 1)
(MeasureSchool)
5. Tag Managers Part 1: The Data Layer
(Digitalgov)
6. The Power of the Google Tag Manager Data Layer
(Koozai)
Top Articles
Latest Posts
Article information

Author: Arielle Torp

Last Updated: 04/05/2023

Views: 5770

Rating: 4 / 5 (41 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Arielle Torp

Birthday: 1997-09-20

Address: 87313 Erdman Vista, North Dustinborough, WA 37563

Phone: +97216742823598

Job: Central Technology Officer

Hobby: Taekwondo, Macrame, Foreign language learning, Kite flying, Cooking, Skiing, Computer programming

Introduction: My name is Arielle Torp, I am a comfortable, kind, zealous, lovely, jolly, colorful, adventurous person who loves writing and wants to share my knowledge and understanding with you.