Skip to content

🌐 Leggi in Italiano

Google Tag Manager

What Google Tag Manager is, what tags, triggers and variables are, and a prototype cookie banner built entirely with Tag Manager.

Alessandro Manias Alessandro Manias Published on · Updated on · 7 min read
Cover image: Google Tag Manager

Contents

What is Google Tag Manager?

Google Tag Manager is a tag management system provided by Google. You can access it here with a Google account.

What is a tag management system?

One example of a tag is the tracking code Google Analytics gives you to install on your site to monitor its traffic.
Google Analytics is a tool for checking the traffic a site receives. There are other similar tools, and a site often runs several of them side by side, each with its own tag.

Below is an example of an Analytics tag:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=YOUR_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'YOUR_ID');
</script>

There are other tools for analysing a website's traffic, such as Yandex Metrica, Facebook Pixel and Hotjar, each offering different data collection and statistical analysis features beyond simple traffic monitoring.

These JavaScript snippets, which in the jargon are called tags, are also used by the various ad delivery platforms such as Google Ad Manager, Google Ads and Google AdSense.

What can you do with Tag Manager?

As you will have gathered from the list above, these tags can crowd a website's pages and need a developer to add new ones or change old ones.

With Tag Manager you can install all these tags and more, update them and test them in a safe mode.

In practice, you install a single tag on your site, the Tag Manager one:

<!-- 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=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','YOUR-ID');</script>
<!-- End Google Tag Manager -->

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=YOUR-ID"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

Through it you can add the other tags from a convenient web dashboard; what's more, before publishing them you can test them in a safe environment.

By safe environment I mean a preview mode in which only you can check whether the new tag you installed works correctly and doesn't interfere with the other tags on your site. Once you have finished checking, you can publish the change and make the new environment live.

The main elements of Tag Manager

Tag Manager is built around three fundamental concepts:

  • Tags
  • Triggers
  • Variables

Tags

Tags are JavaScript snippets like the one I showed you above. They are what gets included in the pages to enable the various features you need.

Tags can be made to run in response to events fired when elements are clicked, but as we will see, tags can be triggered by many kinds of action, both browser-related and tied to specific user actions.

Triggers

Triggers are conditions that tags can be attached to. When the conditions are met, the tags fire.

Triggers can be browser events: the classic Page View, DOM Ready and Window Loaded.
For example, a trigger can fire only when a specific image, or a DOM element with specific classes, is present.
A trigger could also be tied to a click on an anchor with a specific link or a specific class. In short, the dashboard offers plenty of options for firing tags in whatever way suits you.

Variables

Variables are simply values that can be read or set in the JavaScript environment and used in triggers or tags.

What I'm about to show you is an example of what you can do with Tag Manager.

It's an abuse of Tag Manager, in the sense that it isn't designed for this. However, taking inspiration from the Cookies Enabler JS library, you can build a very simple cookie banner that blocks JavaScript and iframes and so handles consent-dependent cookies.

It's worth noting that the base JavaScript loaded by Tag Manager doesn't create any cookies, except when you switch to debug mode.

I realise this isn't something you can use straight away, but I wanted to build a prototype and see whether I could block iframes and scripts from loading, to prevent cookies from being created until the user has consented to them.

This prototype also helps us understand how tags and triggers work together.

The prototype

Let's imagine we want to build a simple cookie banner that unblocks the iframes on a page and triggers loading of the page's scripts.

As for iframes, by stepping in early with JavaScript you can block them from loading and postpone it until the user has decided whether to allow cookies.
For simplicity, though, I chose the same mechanism I use for scripts: replace the script tag's src attribute with a data-src attribute, then either load them or show an alternative message.

JavaScript files, where necessary, have to be handled and blocked directly in the HTML, because Tag Manager's JavaScript obviously can't block them in advance.

What we can do is block them up front at the HTML level and unblock them selectively based on the events that are fired.

The first tag fires on the first page view, which normally happens after the JavaScript has loaded:

<script>
  (function(){
    if ( ! window.$ || ! window.jQuery ) {
      var script = document.createElement('script');
      script.async=true;
      script.src='https://zeptojs.com/zepto.min.js';
      script.addEventListener(
      	'load',
        function(e) {
          dataLayer.push({event: 'ZeptoLoaded'});
        }
      );
      document.body.appendChild(script);
    } else {
      dataLayer.push({event: 'ZeptoLoaded'});
    }
  })();
</script>

The snippet checks whether jQuery is present and, if not, loads Zepto.js, a minimal library that offers jQuery's basic features. When the tag fires it generates a ZeptoLoaded event, which triggers the loading of the next tags.

In Tag Manager you fire an event simply with the following statement:

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

To block JavaScript from running we use a technique also used by Cookies Enabler, which I described above; you can see an example in the following snippet:

<!-- Script  -->
<script data-src="/scripts.js"></script>

<script type="text/plain">
        document.cookie = 'session_cookie_text=session_cookie_text';
        document.cookie = 'expiring_cookie_text=expiring_cookie_text; expires=Sat, 9 May 2022 12:00:00 CET';
</script>

Script tags that load files are blocked by replacing the src attribute with data-src, while inline scripts are blocked by setting their type attribute to text/plain.

To enable script tags selectively we could use classes and re-enable them through those classes according to the user's choices. For example, to selectively enable technical, analytics or profiling cookies we could use different classes such as .tm-technical and .tm-profile.

The blocked script contains:

;(function(){
    document.cookie = 'session_cookie=session_cookie';
    document.cookie = 'expiring_cookie=expiring_cookie; expires=Sat, 9 May 2020 12:00:00 CET';
})();

As for iframes:

<!-- iframe -->
<iframe width="560" height="315" data-src="https://www.youtube.com/embed/C2uTJsjJSfo" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

<iframe width="840" height="472" data-src="https://www.youtube.com/embed/C2uTJsjJSfo"></iframe>

We could use a different class for iframes too. My original idea was to filter iframes and, where necessary, replace www.youtube.com with www.youtube-nocookie.com, the domain YouTube provides for users who don't want cookies set in their browser.

Once Zepto.js has loaded, the cookie banner is loaded.

The banner is built entirely in JavaScript through the library, but we could change the code to use a hidden template on the page.

<script>
  (function($) {
    var $main_box = $('<div>');
    $main_box.css({
      width: '50vw',
      margin: '1rem auto',
      position: 'absolute',
      top: '2rem',
      left: '25vw',
      'text-align': 'center',
      'background-color': '#99999999',
      'padding-bottom': '1rem'
    });
    var $main_title = $('<h1>The cookie banner</h1>');
    var $technical = $('<button>');
    $technical.on(
    	'click',
      	function() {
          $main_box.hide(3000);
          dataLayer.push({event: 'TechnicalCookie'});
        }
    );
    $technical.text('Accept');
    $('body').append($main_box);
    $main_box.append($main_title);
    $main_box.append($technical);
  })(window.jQuery || window.$ || window.Zepto);
</script>

The cookie banner is a simple semi-transparent grey div with a button to accept cookies.

After accepting, JavaScript and iframes are unblocked.

Unblocking happens when the accept button is clicked: the click hides the banner and unblocks execution by firing the following tag:

<script>
  ;(function($) {
    $('[data-src]').each(
      function(i, el) {
        $(el).prop('src', $(el).data('src'));
      }
    );
    $('script[type="text/plain"]').each(
      function(i,el){
        $(el).prop('type','text/javascript');
        eval($(el).text());
      }
    );
  })(window.$ || window.jQuery || window.Zepto);
</script>

As this simple prototype shows, Tag Manager opens up a world of possibilities for managing JavaScript tags.

© 2026 Wordpress e PHP. Statically generated with SvelteKit.