Tải bản đầy đủ (.pdf) (92 trang)

Google tag manager learnings

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (878.81 KB, 92 trang )

100+ GOOGLE TAG MANAGER LEARNINGS

I’ve always been proud to avoid the typical headline clickbait of “Ultimate guide to
pigeon care”, “All you need to know about the Great Vowel Shift”, “Did you know that
you’ve been smoking peyote wrong your whole life?”. I’m ready to make an exception
now by adding a BIG WHOPPING NUMBER to the title. You see, the amount of
knowledge one can accumulate about anything they do on a daily basis is mind-blowing.
It helps if you write a blog about the topic, since creative output is a great way to
organize your thoughts. It also helps to be active in community support, since
problem-solving is an excellent way to accumulate new skills and to hone the edge of
your existing talent.


Now, I already have 50+ GTM Tips written, so it’s not like this is a novel idea, even on
this blog. But this time I just wanted to write short, byte-sized things I’ve learned along
the way, and I want to share them with you.

As you can read from the outrageously baiting title, there should be 100+ tips, but I only
enumerated an even 100. That’s because I want YOU to add your ideas to the end of this
post, and let’s see if we can keep it going. Yes, it’s my shameful attempt to delegate
content creation to the community. I am guilty of that, too, now.

TABLE OF CONTENTS
● Container JavaScript Snippet
○ 1. Initializes the dataLayer
○ 2. Creates the script loader for the GTM library
○ 3. JavaScript snippet should be in <head> but can be (almost)
anywhere
○ 4. Pushes the initial event: 'gtm.js'
○ 5. Multiple container snippets on a page are supported
● Container <noscript> snippet


○ 6. The <noscript> block should be at the very beginning of <body>
○ 7. Only executed by browsers with JavaScript disabled
○ 8. Loads an HTML page in an <iframe>
○ 9. Only the Page View trigger works
○ 10. Use a function() { return true; } Custom JavaScript
variable in the trigger
1


○ 11. Only the Custom Image tag is useful
○ 12. Can utilize “Data Layer” parameters via query parameters
● The dataLayer structure
○ 13. Global JavaScript array
○ 14. You can use a different name than dataLayer
○ 15. Only the .push() method works with GTM
○ 16. Typically only plain objects work with GTM
○ 17. You can use any JavaScript type as a value of a key
○ 18. Only event key can trigger tags
○ 19. You can also .push() a command array
○ 20. Never overwrite, always .push()
○ 21. The array is capped at 300
● GTM’s data model
○ 22. Copies messages queued via dataLayer.push()
○ 23. GTM freezes variable values when a trigger fires
○ 24. Objects are recursively merged
○ 25. Arrays are recursively merged
○ 26. You can run JavaScript methods on existing Data Layer values
with a command array
○ 27. Version 1 vs. Version 2 of the Data Layer Variable
○ 28. google_tag_manager['GTM-XXXX'].dataLayer methods

● Preview mode
○ 29. Preview mode works with a cookie on
www.googletagmanager.com in the preview browser
○ 30. Shows the state of tags, triggers, variables, and Data Layer at
each Data Layer message
○ 31. Summary shows the state at the latest message
○ 32. Variables are resolved multiple times - at least once per
message
○ 33. Preview can be minimized
○ 34. To quit preview, you need to exit preview mode via the GTM UI
○ 35. To quit a shared preview, you need to follow the original link
○ 36. Problems with the preview mode not showing correctly are
most typically due to CSS conflicts
2


○ 37. You can also preview without the debug panel
○ 38. Preview must be refreshed after every change
● Universal Analytics
○ 39. GTM creates a new tracker with every tag instance
○ 40. Settings are not shared across tags
○ 41. You can set a tracker name, but most often this is risky and
unnecessary
○ 42. Use Fields to Set for setting any analytics.js fields
○ 43. If a field has the variable icon, you can use variables in it
● Enhanced Ecommerce
○ 44. Use Data Layer option uses Version 1 of the Data Layer Variable
○ 45. Requires Data Layer object to be syntactically flawless
○ 46. The Currency type is just a string with a monetary value
○ 47. Product-scoped Custom Dimensions and Metrics need to be

formatted correctly
○ 48. Custom JavaScript variable method is more flexible than Use
Data Layer
● Triggers
○ 49. Variables can only be used to check against
○ 50. Use a Custom JavaScript variable to check for dynamic values
○ 51. 'event' is implicit in all but the Custom Event trigger
○ 52. Multiple trigger conditions are AND, multiple triggers are OR
○ 53. Use regular expressions or Custom JavaScript variables to add
optionality in a single trigger
● Auto-event trigger
○ 54. Just Links listens to clicks on <a> elements and their
descendants
○ 55. All Elements listens to all clicks
○ 56. Form listens to a submit event dispatched by a <form> element
○ 57. History Change listens to interactions with the browser history
API
○ 58. Error listens to uncaught JavaScript exceptions
○ 59. All triggers but the Click / All Elements trigger require that the
original event bubble up
3


○ 60. Check Validation checks for event.preventDefault()
○ 61. Wait for Tags pauses the original event, but be careful
○ 62. Enable this trigger when… vs. This trigger fires on…
○ 63. Data Layer object composition of an auto-event
○ 64. Auto-event variable
○ 65. Matches CSS selector with the Click / Form Element built-in
variable

● Custom HTML tags
○ 66. Code is automatically minified
○ 67. Code is injected to the end of <body>
○ 68. Can be used to add any HTML elements
○ 69. The document.write option is fixed to prevent the site from
breaking
○ 70. Variables are automatically renamed in Custom HTML tags, too
● Built-in variables
○ 71. Need to be enabled
○ 72. Click and Form variables are copies of each other
● Custom JavaScript variables
○ 73. Must be anonymous functions
○ 74. Must have a return statement
○ 75. Can be used to return another function
○ 76. Should avoid side effects
○ 77. Can refer to other variables
● Tag sequencing
○ 78. Setup and cleanup are fired with the main tag, regardless of
their own triggers
○ 79. Use onHtmlSuccess() and onHtmlFailure() to signal that the
sequence can continue
○ 80. Use dataLayer.set() to change Data Layer variable values
mid-sequence
● Tag settings
○ 81. Once per page is once per page load, once per event is once per
GTM event
○ 82. Tag priority is for a single GTM event - doesn’t necessarily
4



mean tags are completed in the given order
● Workspaces
○ 83. You will always have at least one workspace
○ 84. When you create a version out of a workspace, that workspace
is deleted
○ 85. You don’t have to update your workspace until you are ready to
create a version
● AMP container
○ 86. No Custom JavaScript or Custom HTML
○ 87. AMP is very restricting
○ 88. Client ID is (currently) ambiguous
○ 89. New triggers, e.g. scroll
○ 90. Can be augmented with the on-page JSON configuration
● GTM for mobile
○ 91. Not the same as GTM for web
○ 92. An SDK you need to download and add to the project
○ 93. GA tracker object is not exposed
○ 94. GTM legacy uses dataLayer
○ 95. Latest version of GTM for mobile uses Firebase
○ 96. You can intercept Firebase events using GTM
○ 97. Firebase GTM has (imperfect) support for GA Enhanced
Ecommerce
● Other stuff
○ 98. Debugging is a complex process
○ 99. Load sequence of GTM’s default events is important to
understand
○ 100. Some ad and content blockers block GTM from loading
○ 101. Use undefined to clear individual keys from Data Layer (upepo
mwindaji)
○ 102. You can track to multiple Universal Analytics properties in the

same container
● Summary
X
5


The Simmer Newsletter

Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava
into your email inbox!

CONTAINER JAVASCRIPT SNIPPET
1. INITIALIZES THE DATALAYER

The JavaScript snippet part of the GTM container has one very important function
(among others). It initializes the window.dataLayer array. Thus, if you haven’t
initialized a dataLayer object yourself, the container snippet will do this for you. This
ensures that dataLayer.push() works within GTM.

2. CREATES THE SCRIPT LOADER FOR THE GTM LIBRARY

Perhaps even more importantly, the JavaScript container snippet creates a <script>
element, which loads the Google Tag Manager container library for your GTM container
ID from Google’s servers.

6


3. JAVASCRIPT SNIPPET SHOULD BE IN <HEAD> BUT CAN BE (ALMOST)
ANYWHERE


The latest (and best) recommendation for placing the JavaScript snippet is to put it in
the <head> of the document. This helps GTM load as early as possible, resulting in
greater tracking accuracy. However, you can execute the JavaScript snippet pretty much
any time during the page load and anywhere in your site code where execution of
JavaScript is possible. The sooner the library loads, though, the more accurate your data
collection will be.

4. PUSHES THE INITIAL EVENT: 'GTM.JS'

The JavaScript snippet also pushes the initial event: 'gtm.js' into dataLayer.
This is an important GTM event. It is used by the All Pages and Page View triggers. Any
Data Layer variables you want to use with these triggers must be added to dataLayer
before the JavaScript container snippet is executed.

7


5. MULTIPLE CONTAINER SNIPPETS ON A PAGE ARE SUPPORTED

You can add multiple JavaScript container snippets on a page. This is officially
supported. The caveat is that they all need to use the same dataLayer name.

CONTAINER <NOSCRIPT> SNIPPET
6. THE <NOSCRIPT> BLOCK SHOULD BE AT THE VERY BEGINNING OF
<BODY>

At the time of writing, the <noscript> block should be added to the very beginning of
<body>. This is the only way that Search Console Verification using the Google Tag
Manager method will work. Naturally, if you don’t care about verifying the site using the

GTM method, nor do you have any use for tracking non-JavaScript visits, you can leave
the <noscript> block out altogether. Just don’t place it in <head> as that would result
in HTML validation issues.

7. ONLY EXECUTED BY BROWSERS WITH JAVASCRIPT DISABLED

8


The <noscript> snippet is only executed by browsers with JavaScript disabled. If you
want to test it, you can disable JavaScript using your browser’s developer tools (e.g.
Chrome).

8. LOADS AN HTML PAGE IN AN <IFRAME>

The block loads an <iframe> element, which fetches its data as an HTML file from
Google Tag Manager’s servers. In essence, this HTML file is your container. The HTML
will contain the image elements you have configured to fire for JavaScript-disabled
visitors.

9. ONLY THE PAGE VIEW TRIGGER WORKS

Because the JavaScript-less GTM can’t run JavaScript (d’oh), only the Page View trigger
is at your disposal. Thus, there’s no dynamic triggers, and no way to wait for the page to
load or anything like that. The Page View trigger is fired when the <iframe> contents
are fetched.

10. USE A FUNCTION() { RETURN TRUE; } CUSTOM JAVASCRIPT
VARIABLE IN THE TRIGGER


9


A very handy way to fire tags only when executed in the <iframe> is to create a Custom
JavaScript Variable with the following content:
1. function() {
2.

return true;

3. }

This variable will only return true if the browser executes it, i.e. executes JavaScript. By
adding {{Variable}} does not equal true as a trigger condition fires the trigger only
in browsers where JavaScript is disabled.

11. ONLY THE CUSTOM IMAGE TAG IS USEFUL

Since the JavaScript-less container can’t execute JavaScript, you are left with just the
Custom Image tag. In other words, you can create image elements that are added
directly into the container HTML. These image elements will then be rendered by the
browser. In fact, you can even do some basic Google Analytics tracking using an image
tag, since GA requests are basically image pixels. See this LunaMetric guide for
inspiration.

12. CAN UTILIZE “DATA LAYER” PARAMETERS VIA QUERY PARAMETERS

10



You can feed “Data Layer” values to the container HTML using query parameters in the
<iframe> src attribute value. The query parameters need to be added as key-value
pairs, and the keys that you add can then be used in Data Layer variables. For further
details, see the Bounteous guide linked to in the previous paragraph, or check the guide
I’ve written.

THE DATALAYER STRUCTURE
13. GLOBAL JAVASCRIPT ARRAY

The dataLayer structure is a global JavaScript array, and can thus be accessed in any
site code that can also access the window object. It’s a good idea to always prefix the
dataLayer name with window. to avoid conflicts with any locally scoped structures
that use the same name.

14. YOU CAN USE A DIFFERENT NAME THAN DATALAYER

You can change the name of this global structure in the JavaScript container snippet.
Just remember to always use this new name when adding messages to dataLayer!

11


15. ONLY THE .PUSH() METHOD WORKS WITH GTM

Google Tag Manager only reacts to the .push() method. You can .splice(),
.slice(), .shift() and .pop() all you like. GTM only listens for .push()
commands.

16. TYPICALLY ONLY PLAIN OBJECTS WORK WITH GTM


The most common way to feed data to Google Tag Manager is using plain objects. Each
object contains one or more key-value pairs. These key-value pairs are then translated
into Data Layer variables, which you can create in Google Tag Manager to fetch values
from the Data Layer.
4. var plainObject = {
5.

someKey: 'someValue',

6.

someOtherKey: 'someOtherValue'

7. };
8. window.dataLayer.push(plainObject);

12


17. YOU CAN USE ANY JAVASCRIPT TYPE AS A VALUE OF A KEY

All JavaScript types are supported as values when you push your dataLayer messages.
When you create a Data Layer variable in GTM, it will contain a reference to whatever
the value of the key is, regardless of type.
9. window.dataLayer.push({
10.

type_number: 5,

11.


type_string: 'hello',

12.

type_object: { someKey: 'someValue' },

13.

type_array: [1,2,3,4],

14.

type_function: function() { return 'hello'!; },

15.

type_boolean: true

16. });

18. ONLY EVENT KEY CAN TRIGGER TAGS

Only a message with an event: 'someValue' key-value pair can trigger tags. Any
object without an 'event' key is treated as just a “message”, and has no triggering
power of its own.

19. YOU CAN ALSO .PUSH() A COMMAND ARRAY

13



There’s a special command array you can .push() into dataLayer if you want to
execute methods for values already in the data model. So technically it’s not just plain
objects that dataLayer digests. There’s more about this in tip #26.

20. NEVER OVERWRITE, ALWAYS .PUSH()

I usually hate to dole out best practices, so consider this a fact of life instead. Never,
ever, ever, ever use this syntax:
17. var dataLayer = [{...}];

It’s destructive. If this command is executed after the GTM container snippet or after
you’ve already established a dataLayer object, you will end up overwriting the existing
object with this newly initialized structure. Worst-case scenario (surprisingly common)
is that you’ll end up breaking GTM, since you also overwrite the custom .push()
listener added by the container library.

Prefer this syntax instead:
18. window.dataLayer = window.dataLayer || [];
19. window.dataLayer.push({...});

14


21. THE ARRAY IS CAPPED AT 300

This is perhaps more obscure, but in addition to adding a .push() listener, the GTM
container library also caps the length of the dataLayer structure at 300. This means
that when you .push() the 301st item into dataLayer, the first/oldest item in

dataLayer is removed. As you will learn in the next section, this has no impact on
GTM’s data model. It just caps the dataLayer structure itself.

GTM’S DATA MODEL
22. COPIES MESSAGES QUEUED VIA DATALAYER.PUSH()

When you use the Data Layer Variable, Google Tag Manager doesn’t fetch the value
from the dataLayer array. Instead, it polls its own internal data model to see if any
value has been pushed to the given key (or variable name). If a value is found, GTM
returns it. This means that GTM’s internal data model has access to the most recently
pushed value for any given key.

23. GTM FREEZES VARIABLE VALUES WHEN A TRIGGER FIRES

15


Triggers only fire when the key 'event' is pushed into dataLayer. When this
happens, GTM “freezes” the state of the container, and any tags that fire on this trigger
will only have access to the current state of the internal data model. Thus, if you want to
push values into dataLayer so that they become available to a tag that triggers on the
site, these values need to be pushed before or in the same object as the 'event' that
triggers the tag.

24. OBJECTS ARE RECURSIVELY MERGED

Recursive merge is one of the more complex concepts to understand. When you work
with primitive values (strings, numbers, booleans, for example), the internal data model
of GTM only has access to whatever was most recently pushed into a key whose value is
one of these primitive types. However, when you work with structured objects and

arrays, it’s more complicated.

When you push an object into dataLayer, GTM goes through each key in this object,
and only overwrites those that have shared keys and primitive values (or where the type
changes). New keys are simply added to the existing object value.

16


When pushing an object to a key that already contains an object with the same keys,
only the keys that have primitive values or a different type are overwritten. All others are
simply updated.

25. ARRAYS ARE RECURSIVELY MERGED

In JavaScript, arrays are structured objects, too, where the keys are index numbers that
start from 0. So when you push an array into a key that already had an array, these two
arrays are recursively merged starting from index 0, and any indices that are not
modified remain the same.

26. YOU CAN RUN JAVASCRIPT METHODS ON EXISTING DATA LAYER
VALUES WITH A COMMAND ARRAY

What if you already have an array in a key, but instead of merging or overwriting you
want to add values to it, i.e. push items to the end of the array? You can use a special
17


command array that you push into dataLayer. The first element in the array is a
string that contains the key name and the command you want to execute, and all the

other items are passed as arguments to the command.

27. VERSION 1 VS. VERSION 2 OF THE DATA LAYER VARIABLE

You’ve probably noticed that you can choose a version when using the Data Layer
Variable. There are some very important differences between the two.

Version 2 supports deep structures with dot notation. If you want to access array
indices, you need to use dot notation too (products.0.name rather than
products[0].name). Only Version 2 supports recursive merge.

Version 1 does not support dot notation, and it only fetches the most recently pushed
value whether it’s an object or not. Thus there’s no recursive merge - what you push is
what you get.

28. GOOGLE_TAG_MANAGER['GTM-XXXX'].DATALAYER METHODS

18


If you want to access values stored in Google Tag Manager’s data model from outside
GTM or without using a Data Layer Variable, you can use the google_tag_manager
interface.

google_tag_manager['GTM-XXXX'].dataLayer.get('keyName') fetches the
value stored in GTM’s data model for variable name keyName.

google_tag_manager['GTM-XXXX'].dataLayer.set('keyName',
'someValue') sets the value of keyName to someValue in GTM’s data model. This
is the equivalent to using dataLayer.push({keyName: 'someValue'});


google_tag_manager['GTM-XXXX'].dataLayer.reset() purges GTM’s data
model, removing all stored keys.

PREVIEW MODE
29. PREVIEW MODE WORKS WITH A COOKIE ON
WWW.GOOGLETAGMANAGER.COM IN THE PREVIEW BROWSER

19


When you enter GTM’s Preview Mode, you are transported through the domain
www.googletagmanager.com (the same domain that serves the gtm.js library), during
which a cookie is written in your browser for that domain.

When you then visit your website, the request for the gtm.js library identifies that you
have the Preview mode cookie written on www.googletagmanager.com, and the preview
container library is returned instead. So what you’re basically dealing with is a
third-party cookie, even though the cookie isn’t set while browsing the site itself.

30. SHOWS THE STATE OF TAGS, TRIGGERS, VARIABLES, AND DATA
LAYER AT EACH DATA LAYER MESSAGE

Preview mode is a great way to understand how Google Tag Manager works. The
navigation in the left column is a chronological (oldest at the bottom) list of messages
that have been pushed into dataLayer. By selecting a message, you can see if any tags
fired during that message, and you can see the state of tags, variables, and triggers at the
time of the message.

20



What you see is what you get. If the variable does not have a value at the time of the
message, it means that any tags that fire for that message will not have access to any
value if using that variable. This is why it’s important to understand that if you want
to use a variable, it must have a value when the message that triggers the tag
is pushed into dataLayer.

31. SUMMARY SHOWS THE STATE AT THE LATEST MESSAGE

Summary is not a message itself. It’s a recap of what the state of the container is after
the latest message has fired. Note that if you have Summary (or any other message, for
that matter) selected, and you select a tag that fired in an earlier message, the tag might
have different values than what you’d expect. That’s because when you select a message
(or Summary), the variables reflect what their values are at the time of the selected
message. This way tags can show different values from those that were actually used.

That’s why it’s really important to start debugging by selecting the message that fired the
tag. Any other message and you might see confusing data.

32. VARIABLES ARE RESOLVED MULTIPLE TIMES - AT LEAST ONCE PER
MESSAGE

21


If you’ve ever created a variable with side effects and then gone to preview mode, you
might have been surprised at what happens. For example, create a Custom JavaScript
Variable with this:
20. function() {

21.

window._testCount = window._testCount || 1;

22.

return window.alert(window._testCount++);

23. }

Now when you go to Preview mode, you’ll see a bunch of alerts with a number that
increments with each alert. Depending on how many messages are pushed into
dataLayer and how many tags use this variable, you might see a huge number in the last
alert box.

This is because GTM resolves variables in Preview mode multiple times.
Preview mode needs to resolve the variables at least once per message pushed into
dataLayer. Why? Because Preview mode must be able to tell you the value of each
variable in each tag, trigger, variable, and message.

In a live container, variables won’t be resolve this many times. Most likely they are only
resolved when they are directly invoked, e.g. in triggers and tags upon injection.

22


33. PREVIEW CAN BE MINIMIZED

The Preview mode panel can be visually obstructive, so it’s a good thing the developers
added a minimize button some time ago:


After clicking it, you can bring the panel back up by clicking the small DEBUG ^ icon in
the lower right corner of the window.

34. TO QUIT PREVIEW, YOU NEED TO EXIT PREVIEW MODE VIA THE GTM
UI

The easiest way to quit Preview mode is to go to the Google Tag Manager user interface
and click the “Leave preview mode” link:

23


You can also go to your browser’s content settings, and delete all cookies written on the
www.googletagmanager.com domain. This works with Shared Preview, too.

Wouldn’t it be handy if you could just quit Preview mode from the panel itself on the
site? Yes, I think so too.

35. TO QUIT A SHARED PREVIEW, YOU NEED TO FOLLOW THE ORIGINAL
LINK

If you want to quit Preview mode that has been shared with you, you should follow the
original Share Preview link and click “Exit preview and debug mode”.

Note that you can also delete the cookies as described in the previous tip.

24



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×