Wednesday, April 24, 2024
No menu items!
HomeData Analytics and Visualization5 Advanced Google Tag Manager tips

5 Advanced Google Tag Manager tips

If you are already considering yourself an intermediate or maybe even advanced Google Tag Manager user, you are probably looking for new ways to improve your GTM skills to be able to solve more complex challenges.

That’s where things like JavaScript, Document Object Model (DOM), and similar topics become more important. Those topics are a tough nut to crack and cannot be explained in a single blog post. However, I wanted to give you quick tips that you can apply almost immediately without losing yourself among countless documentations and courses.

In this blog post, I will share 5 advanced Google Tag Manager tips that I use very often in my setups. Hopefully, they will help you too.


Video tutorial

If you prefer video content, here’s a tutorial from my Youtube channel.

 

#1. document.querySelectorAll()

Let’s say that you want to track clicks of certain elements on a page (menu items). Those links have no IDs thus you have two options: cooperate with a developer to get them implemented or try to go advanced and use CSS selectors (I explain them in my Intermediate/Advanced GTM course).

You come up with a selector that works on all elements you need. But how can you be sure that the selector is correct and will work only with those elements that you want to track? How can you be sure that CSS selector will not falsely return some unrelated element (e.g. footer links or sidebar links)?

Enter document.querySelectorAll(). It’s a method that will show you the list of all elements on a page that match your CSS selector. If it returns too many items, you need to do a better job and make your selector more specific.

To try this, open the JavaScript console in your browser’s developer tools, and enter the following command:

document.querySelectorAll(“your_css_selector”)

Replace the your_css_selector with the actual CSS selector you wish to test against. In my case, the selector is “.site-nav__link”.

Hit enter. What I’ll see is the list of all the elements on a page that use this class. In the example below, I got 5 elements. You can tell that from the number next to the NodeList and if I click the triangle next to it, I’ll see the list of all HTML elements that use that site-nav__link CSS class).

If the method returned more elements, I would have to update my selector and make it more precise.

 

#2. JSON.parse()

Sometimes, you might have conversion data in the data layer but it is stored as a string, not as an object (we know it’s a string because it is surrounded by quotation marks).

What if you want to access only a certain key from that string, e.g. form_id? The long way would be to use string methods and parse the text. But that’s overkill.

If you have an object (read: complex structure) stored as a string (read: plain text), there is a handy method called JSON.parse(). It takes that string and will return the parsed object. This allows you to quickly get the needed key from the object.

For example, let’s say that you are tracking form submissions and this is what you have on a “thank you” page in the data layer:

To resolve this, you should first create a data layer variable that returns the string. I called that variable dlv – formData

And then create a Custom JavaScript variable that will pass the data layer variable to the JSON.parse() method. Here’s the code of the Custom JavaScript variable:

function() {
   if ({{dlv – formData}}) {
      return JSON.parse({{dlv – formData}})
   }
}

Important: the name of the data layer variable in the code must be EXACTLY the same as you have named your data layer variable in the GTM interface.

If I save all of these changes, then enable the preview mode, and then submit the form again, here’s what I would see. Data Layer Variable returns the object as a string (surround by quotation marks).

But the Custom JS variable then takes the data layer variable, parses it, and returns the object (not surrounded by quotation marks).

Now, how can you access a particular key in that object, e.g. form_id? You have to update the Custom JS variable like this:

I added a .form_id because that is how you access keys in the object. If I wanted to access form_name, the code of the variable would be this:

function() {
   if ({{dlv – formData}}) {
      return JSON.parse({{dlv – formData}}).form_name
   }
}

 

#3. split() and decodeURIComponent()

Let’s say that I want to extract a part of the URL. That URL looks like this: https://www.analyticsmania.com/ google-tag-manager-recipes /this-is-a-very-cool-%26-important-page/?gtm_debug=x and I want to extract the part that is this-is-a-very-cool-%26-important-page.

There are two challenges here:

we need to somehow get only that part of the URL
that part contains a weird %26What is it and how to get rid of it?

Note: there are alternative methods to extract URL parts but in this guide, I will explain this one.

One of the ways how you can extract a part of the text (string) is by using the split() method. You pass a separate to it and then it will return an array of all strings.

In the JavaScript console of the browser, enter the following command:

window.location.href.split(‘/’)

window.location.href returns the full URL you see in the browser address bar. In my case, it will return https://www.analyticsmania.com/ google-tag-manager-recipes /this-is-a-very-cool-%26-important-page/?gtm_debug=x

.split(‘/’) means that this URL will be split into multiple strings (texts) every time a slash (/) is spotted. In this case, the method will return an array of 6 items:

https
[empty space] (because there were two consecutive slashes in https:// and there was nothing between them
www.analyticsmania.com
google-tag-manager-recipes
this-is-a-very-cool-%26-important-page
gtm_debug=x

Now, I want to access the 5th member of that array, this-is-a-very-cool-%26-important-page. In JavaScript, indexing starts from 0, thus the index of the 5th member is 4.

If I want to access that member, I have to use the this [4].

Let’s update our JS code:

window.location.href.split(‘/’)[4]

This will split the URL and will return the 5th member in the array, therefore the output will be this-is-a-very-cool-%26-important-page.

What about that %26? This is an encoded ampersand (&). If you want this to be displayed as & instead of %26, you will need to use the method called decodeURIComponent().

Let’s update the JavaScript code one more time.

decodeURIComponent(window.location.href.split(‘/’)[4])

Now it will return this-is-a-very-cool-&-important-page.

If you want to use this code in GTM as a variable, create a Custom JavaScript variable with the following code (we have already built most of that):

function() {
  return decodeURIComponent(window.location.href.split(‘/’)[4])
}

And now you can use this in any tag you need.


 

#4. Extract price from the page

Let’s say that you are tracking conversions and you see the price displayed on the “Order Confirmation” page. How can you use it in your tags? One of the ways can be to scrape the site with a Custom JavaScript variable.

Although this is not as recommended (working with the data layer is much more robust), in some cases, you just have no other option (maybe no developer is available in your project?).

The method of scraping the price depends on how the price is displayed on a page. Does it look like this 12,000.00 USD? Or maybe $12.00? Or maybe even something else? The final code depends on how the price is displayed and all options are covered in this blog post.  So make sure you read it.

 

#5. Return X or Y

The last tip of this blog post is related to using multiple variables. Let’s say that after a successful payment, the visitor is redirected to the order confirmation page. The URL looks like this: https://www.mysite.com/thanks/?order_id=123abc.

You want to send that ID to Google Ads. “Create the URL variable and use it in a tag” you might say. That’s correct. But what if your website is coded in a weird way? On some order confirmation pages, the id is in the URL, but on others, that ID is in the data layer.

That will leave you with two variables, URL variable and data layer variable. Both can contain the same information but in most cases, you will have either one or another available on the confirmation page.

How can you instruct Google Tag Manager to use one or another? A custom JavaScript variable is the answer. The code is fairly simple:

function() {
return {{variable 1}} || {{variable 2}};
}

The || in the code means OR. So you are instructing the Custom JS variable to return the first variable. If it is undefined (read: is not available), then it will try to return the 2nd variable. If it is also unavailable, then the variable will return undefined.

Obviously, you should replace {{variable 1}} and {{variable 2}} with the actual names of your variables.

 

Advanced Google Tag Manager tips: Final words

Hopefully, at least some of these quick tips taught you something new. Out of these, the most popular technique in my stack is document.querySeletorAll(). I constantly check whether my conditions are not returning unwanted elements.

If some of these tips looked unclear, watch this video tutorial. Maybe that will help.


The post 5 Advanced Google Tag Manager tips appeared first on Analytics Mania.

Read MoreAnalytics Mania

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments