1. Trang chủ
  2. » Công Nghệ Thông Tin

Google tag manager learnings

92 6 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 92
Dung lượng 878,81 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

GOOGLE TAG MANAGER LEARNINGS 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.

Trang 1

100+ GOOGLE TAG MANAGER LEARNINGS

I’ve always been proud to avoid the typical headline clickbait of “Ultimate guide topigeon care”, “All you need to know about the Great Vowel Shift”, “Did you know thatyou’ve been smoking peyote wrong your whole life?” I’m ready to make an exceptionnow 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 ofyour existing talent

Trang 2

Now, I already have 50+GTM Tipswritten, so it’s not like this is a novel idea, even onthis blog But this time I just wanted to write short, byte-sized things I’ve learned alongthe 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 onlyenumerated an even 100 That’s because I want YOU to add your ideas to the end of thispost, and let’s see if we can keep it going Yes, it’s my shameful attempt to delegatecontent 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

Trang 3

○ 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 di erent 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 valueswith 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.comin the preview browser

○ 30 Shows the state of tags, triggers, variables, and Data Layer ateach 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

Trang 4

○ 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 andunnecessary

○ 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 beformatted correctly

○ 48 Custom JavaScript variable method is more flexible than UseData 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 addoptionality 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 historyAPI

○ 58 Error listens to uncaught JavaScript exceptions

○ 59 All triggers but the Click / All Elements trigger require that theoriginal event bubble up

Trang 5

○ 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-invariable

● 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 frombreaking

○ 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 e ects

○ 77 Can refer to other variables

Trang 6

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 tocreate 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 stu

○ 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 (upepomwindaji)

○ 102 You can track to multiple Universal Analytics properties in thesame container

● Summary

X

Trang 7

The Simmer Newsletter

Subscribe to theSimmer newsletterto 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 Thisensures 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

Trang 8

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 ingreater tracking accuracy However, you can execute the JavaScript snippet pretty muchany 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 datacollection 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 AnyData Layer variables you want to use with these triggers must be added to dataLayer

before the JavaScript container snippet is executed.

Trang 9

5 MULTIPLE CONTAINER SNIPPETS ON A PAGE ARE SUPPORTED

You can add multiple JavaScript container snippets on a page This isofficially

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 thatSearch Console Verificationusing the Google TagManager method will work Naturally, if you don’t care about verifying the site using theGTM method, nor do you have any use for tracking non-JavaScript visits, you can leavethe <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

Trang 10

The <noscript> snippet is only executed by browsers with JavaScript disabled If youwant 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 fromGoogle Tag Manager’s servers In essence, this HTML file is your container The HTMLwill contain the image elements you have configured to fire for JavaScript-disabledvisitors

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 toload or anything like that The Page View trigger is fired when the <iframe> contentsare fetched

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

Trang 11

A very handy way to fire tags only when executed in the <iframe> is to create a CustomJavaScript 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 theCustom 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 thebrowser In fact, you can even do some basic Google Analytics tracking using an imagetag, since GA requests are basically image pixels Seethis LunaMetric guidefor

inspiration

12 CAN UTILIZE “DATA LAYER” PARAMETERS VIA QUERY PARAMETERS

Trang 12

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-valuepairs, and the keys that you add can then be used in Data Layer variables For furtherdetails, see the Bounteous guide linked to in the previous paragraph, or check theguideI’ve written

THE DATALAYER STRUCTURE

13 GLOBAL JAVASCRIPT ARRAY

The dataLayer structure is a global JavaScript array, and can thus be accessed in anysite code that can also access the window object It’s a good idea to always prefix thedataLayer name with window to avoid conflicts with any locally scoped structuresthat 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!

Trang 13

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 Eachobject contains one or more key-value pairs These key-value pairs are then translatedinto Data Layer variables, which you can create in Google Tag Manager to fetch valuesfrom the Data Layer

Trang 14

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 whateverthe value of the key is, regardless of type

18 ONLY EVENT KEY CAN TRIGGER TAGS

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

19 YOU CAN ALSO PUSH() A COMMAND ARRAY

Trang 15

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 plainobjects 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 afteryou’ve already established a dataLayer object, you will end up overwriting the existingobject 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({ });

Trang 16

21 THE ARRAY IS CAPPED AT 300

This is perhaps more obscure, but in addition to adding a push() listener, the GTMcontainer 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 onGTM’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 valuefrom the dataLayer array Instead, it polls its owninternal data modelto see if anyvalue 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

Trang 17

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 triggerwill only have access to the current state of the internal data model Thus, if you want topush values into dataLayer so that they become available to a tag that triggers on thesite, these values need to be pushed before or in the same object as the 'event' thattriggers the tag

24 OBJECTS ARE RECURSIVELY MERGED

Recursive merge is one of the more complex concepts to understand When you workwith 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 isone of these primitive types However, when you work with structured objects andarrays, 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 typechanges) New keys are simply added to the existing object value

Trang 18

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 aresimply updated.

25 ARRAYS ARE RECURSIVELY MERGED

In JavaScript, arrays are structured objects, too, where the keys are index numbers thatstart from 0 So when you push an array into a key that already had an array, these twoarrays 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 youwant to add values to it, i.e push items to the end of the array? You can use a special

Trang 19

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 theother 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 canchoose 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 iswhat you get

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

Trang 20

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

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 datamodel, removing all stored keys

PREVIEW MODE

29 PREVIEW MODE WORKS WITH A COOKIE ON

WWW.GOOGLETAGMANAGER.COM IN THE PREVIEW BROWSER

Trang 21

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), duringwhich 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 youhave the Preview mode cookie written onwww.googletagmanager.com, and the previewcontainer 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 messagesthat have been pushed into dataLayer By selecting a message, you can see if any tagsfired during that message, and you can see the state of tags, variables, and triggers at thetime of the message

Trang 22

What you see is what you get If the variable does not have a value at the time of themessage, 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, forthat matter) selected, and you select a tag that fired in an earlier message, the tag mighthave 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 thetag Any other message and you might see confusing data

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

Trang 23

If you’ve ever created a variable with side effects and then gone to preview mode, youmight have been surprised at what happens For example, create a Custom JavaScriptVariable with this:

20.function() {

21. window._testCount = window._testCount || 1;

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

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 onlyresolved when they are directly invoked, e.g in triggers and tags upon injection

Trang 24

33 PREVIEW CAN BE MINIMIZED

The Preview mode panel can be visually obstructive, so it’s a good thing the developersadded 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 interfaceand click the “Leave preview mode” link:

Trang 25

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

Wouldn’t it be handy if you could just quit Preview mode from the panel itself on thesite? 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 theoriginal Share Preview link and click “Exit preview and debug mode”

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

Trang 26

36 PROBLEMS WITH THE PREVIEW MODE NOT SHOWING CORRECTLY ARE MOST TYPICALLY DUE TO CSS CONFLICTS

Sometimes you might not see a Preview mode on a website at all Other times the panelmight be buggy, such as being partly transparent or completely white

In these cases, it’s most often a CSS conflict with the site code GTM loads the panel onthe website itself, so style conflicts can arise if they share the same namespace

If this happens, your best bet is to contact the developer team via the Send Feedbacklink in the UI, or by posting the issue in theProduct Forums

37 YOU CAN ALSO PREVIEW WITHOUT THE DEBUG PANEL

Note that you can also preview a container on the site without the benefit of the debugpanel Why you’d want to do this when you can minimize the debug panel escapes me,but to do so you need to click the Share Preview link in the GTM UI, uncheck “Turn ondebugging when previewing”, and then follow the link in your browser This sets your

Trang 27

browser into Preview mode without showing the debug panel.

38 PREVIEW MUST BE REFRESHED AFTER EVERY CHANGE

GTM doesn’t auto-refresh the Preview mode when you save changes in your container.You need to click the “Refresh” link to update the preview mode for yourself and anyonewith the preview link

UNIVERSAL ANALYTICS

39 GTM CREATES A NEW TRACKER WITH EVERY TAG INSTANCE

Unlike on-page Universal Analytics (analytics.js), Google Tag Manager creates a new,unique tracker object with every single tag that fires, even if they use the same template

Trang 28

This might not be the most elegant technical design ever, but it’s necessary in how GTMstructures Universal Analytics tags Basically each tag is its own sandbox, and settingsare not shared from tag to tag.

40 SETTINGS ARE NOT SHARED ACROSS TAGS

Because each tag has a unique tracker, no settings are shared from tag to tag This isvery much unlike on-page Universal Analytics, where you create a single tracker andthen invoke that tracker in commands like gắtrackerNamẹsend',

'pageview');

If you want to share settings of a single tag with other tags, currently you need to set the

Tracker Name field in the tag settings But before you do, read the next tip.

41 YOU CAN SET A TRACKER NAME, BUT MOST OFTEN THIS IS RISKY AND UNNECESSARY

If you do set the Tracker Name, you are likely to run into a host of problems First of all

Trang 29

-ALL settings are shared across the two tags This is because GTM sets all fields andCustom Dimension / Metrics on the tracker object itself rather than just the hit Soyou’ll need to take great care to reset any fields that you don’t want values to leak into.

Until GTM introduces some type of shared tag settings feature, I suggest avoiding thetracker name setting and working with GTM variables instead If you want a setting toapply across two or more tags, just replicate the setting in each tag and use a variable topopulate the same value in all the tags

42 USE FIELDS TO SET FOR SETTING ANY ANALYTICS.JS FIELDS

You can use Fields to Set to set anyanalytics.jsfields These fields are set on the trackerobject itself (see previous tip), but will work as if set on the hit itself

You can also addMeasurement Protocol parametersto Fields to Set, but this is, in mostcases, unnecessary

43 IF A FIELD HAS THE VARIABLE ICON, YOU CAN USE VARIABLES IN IT

Fields in Google Tag Manager support adding a variable if the field has the variable iconnext to it

Trang 30

By clicking the icon, a list of all available variables pops up You can also use the

auto-complete feature by typing {{ into the field, after which an auto-complete menushows, and you can continue typing to find the variable you’re looking for

ENHANCED ECOMMERCE

44 USE DATA LAYER OPTION USES VERSION 1 OF THE DATA LAYER

VARIABLE

When you select the Use Data Layer option in your Enhanced Ecommerce enabled

Universal Analytics tags, GTM uses the Version 1 of the Data Layer Variable to locate themost recently pushed ecommerce key from the Data Layer

Read that again GTM only has access to the most recently pushed Enhanced

Trang 31

Ecommerce payload in dataLayer This means that if you first push impressions, forexample, but don’t fire a tag, and then you push a Product Detail View which does fire atag, that tag will only access the Product Detail View data The impressions data is lost

in cyberspace, due to no tag firing when it was pushed to dataLayer To avert this,either make sure you always add an event to all your Enhanced Ecommerce pushes,and always use a Custom Event Trigger to fire an Enhanced Ecommerce enable tag

Alternatively, you can use the far more flexible Custom JavaScript variable method

45 REQUIRES DATA LAYER OBJECT TO BE SYNTACTICALLY FLAWLESS

Enhanced Ecommerce is a bit different from how Data Layer typically works Generally,you can push any key-value pairs into Data Layer, because you can always transformand mutate them in the GTM UI later on However, when working with EnhancedEcommerce, either via “Use Data Layer” or the Custom JavaScript Variable method, the

payload must be syntactically accurate It must have all the required keys, it must be structured correctly, and it must obey certain limitations to the structure (more detailsabout structure)

You should always make sure you’re following the officialdeveloper guideto the letter

46 THE CURRENCY TYPE IS JUST A STRING WITH A MONETARY VALUE

Trang 32

If you read the officialEnhanced Ecommerce developer guide, you might have noticedreferences to a type called “currency”.

Well, there’s no such data type in JavaScript What the guide means is a string that has amonetary value (without currency symbol) Don’t use a thousand separator (e.g “1045.99”), and use the period as the decimal character

A valid “currency” type would be "1045.99" Invalid types would be "1 045.99" and

"1045,99" Due to loose typing in JavaScript, you could just as well pass it as a

number 1045.99, but that will definitely lead to problems if the number is incorrectlyformatted

47 PRODUCT-SCOPED CUSTOM DIMENSIONS AND METRICS NEED TO BE FORMATTED CORRECTLY

Product-scoped Custom Dimensions and Metricsneed to be formatted in a certain way

to work With regular Custom Dimensions and Metrics, all you need to do is add them tothe tags under the respective tag settings

Trang 33

However, in Enhanced Ecommerce, all the information must be in the payload WithProduct-scoped Custom Dimensions and Metrics, this data must be in the productsarray, under each individual product you want to add the dimensions and metrics to.The dimensions and metrics must be named dimensionX and metricX where X is theindex number for the given custom variable.

Trang 34

48 CUSTOM JAVASCRIPT VARIABLE METHOD IS MORE FLEXIBLE THAN USE DATA LAYER

I always implement Enhanced Ecommerce using theCustom JavaScript variable

method It gives me so much more flexibility, as I can simply create the original

dataLayer object as semantically unambiguous as possible, and then use the CustomJavaScript variable to mutate the object into the state the Enhanced Ecommerce

requires Why? Because I have plenty of other platforms that need the ecommerce data,too, and they might not be happy with the way that Google Tag Manager enforces aspecific structure

Trang 35

The Custom JavaScript variable itself is simple All you need to do is make sure it

returns a valid Enhanced Ecommerce object as required by Google Tag Manager

TRIGGERS

49 VARIABLES CAN ONLY BE USED TO CHECK AGAINST

This is perhaps slightly oddly worded, but what I mean is that you can only use a

variable as the thing in the trigger whose value you are checking You can’t use a variable

as the condition value itself

50 USE A CUSTOM JAVASCRIPT VARIABLE TO CHECK FOR DYNAMIC

Trang 36

If you DO want to check against dynamic values in your triggers, you can always use aCustom JavaScript variable Let’s say you want to check if the clicked URL contains thecurrent page hostname Why? Because you want a trigger that fires only for clicks onlinks that take the user away from the website This is what the Custom JavaScriptvariable might look like:

51 'EVENT' IS IMPLICIT IN ALL BUT THE CUSTOM EVENT TRIGGER

All triggers require an event key in dataLayer to fire Thus, when you create a trigger,they check for the value of event, and if there’s a match the trigger fires Only the

Custom Event trigger requires you to explicitly state the value of event you want to fire

Trang 37

against Here are the basic trigger types and their implicit event values:

● DOM Ready - gtm.dom

● Page View - gtm.js

● Window Loaded - gtm.load

● Click / All Elements - gtm.click

● Click / Just Links - gtm.linkClick

● Form submission - gtm.formSubmit

● History Change - gtm.historyChange

● JavaScript Error - gtm.pageError

● Timer - gtm.timer

● Scroll Depth - gtm.scrollDepth

● YouTube Video - gtm.video

52 MULTIPLE TRIGGER CONDITIONS ARE AND, MULTIPLE TRIGGERS ARE OR

Multiple conditions in a single trigger must ALL match for the trigger to fire Thus a

trigger like this should never work:

Trang 38

Why won’t it work? Because the hostname of the current page can’t be two things atonce.

If you add multiple triggers to a tag, then any one of these will fire the tag So, if

you want your tag to fire when the page hostname is eitherwww.domain.comor

www.other-domain.com, you can create two triggers, one for each hostname, and addboth to the tag

53 USE REGULAR EXPRESSIONS OR CUSTOM JAVASCRIPT VARIABLES TO ADD OPTIONALITY IN A SINGLE TRIGGER

There’s an easier way to introduce optionality, though First, if it’s a simple string check,you can always useregular expressions

If you have more complex logic, a Custom JavaScript variable is your best friend, again

68.function() {

69. var hn = {{Page Hostname}},

Trang 39

71. if (hn === 'www.mydomain.com' && ut === 'visitor') {

When you create a Just Links trigger, it listens to clicks on <a> elements and their

descendants When a click is registered, Google Tag Manager checks if there is a linknode wrapping the clicked element, and if there is, GTM stores a reference to the link inthe dataLayer

Trang 40

leverage with Auto-event variables.

55 ALL ELEMENTS LISTENS TO ALL CLICKS

All Elements, on the other hand, listens to all clicks and returns the element that wasactually clicked In the HTML example above, the All Elements trigger would return the

<span> element because that’s the element that was actually clicked

56 FORM LISTENS TO A SUBMIT EVENT DISPATCHED BY A <FORM>

ELEMENT

The Form trigger only works with an actual <form> element submitted with defaultHTML form functionality This means that there actually needs to be a submit eventdispatched by the form, and it must be allowed to bubble up

Ngày đăng: 26/04/2022, 11:18

TỪ KHÓA LIÊN QUAN