How to ‘Autotrack’ With GTM

How to ‘Autotrack’ With GTM

Websites today are much more complex and interactive than they were a decade ago. For most sites, tracking only basic pageviews provides a very limited view of activity on the site. Yet this is precisely what an “out-of-the-box” analytics implementation offers.GTM Built In Variables

Downloads, form submissions, video views, dynamic page loads, and on-page social sharing are just a few common interactions that are invisible to basic tracking implementations. As a result, an “out-of-the-box” implementation provides an incomplete and possibly inaccurate picture of your customers and their interactions with your site. What good are pageviews when what you really care about are brochure downloads, lead form submissions, or product purchases?

If the interactions that are key to your success are invisible to your analytics, it will be impossible to obtain any useful insights about your customers, and ultimately you won’t gain any meaningful value from analytics.

Of course, tracking anything beyond basic pageviews requires varying levels of time and effort in order to customize your implementation. With this in mind, Google recently announced an Autotrack plugin for Google Analytics, allowing you to track a variety of common site interactions with “minimal” effort.

However, we can’t help but feel like Autotrack is a few years past its time. Over the last 3+ years, our preferred method of deploying GA and building customized implementations has been Google Tag Manager (GTM). Yet, Autotrack is designed for use with the default JavaScript tracking snippet and requires customizations to be hard-coded into each page. So it’s not as automatic as its name suggests.

Autotrack claims to be intended for sites that are currently not customizing their implementation. “If you’re just using the default tracking snippet today, you should consider using Autotrack,” says the post on the GA blog. However, if this is you, we highly recommend migrating to GTM instead of further tying your analytics to hard-coded on-page tags and scripts.

So, what if you’re already using GTM and would like to implement some of the features offered by the Autotrack plugin? You cannot easily leverage Autotrack directly, but using GTM, you can implement all the same “auto” tracking features with a comparable amount of effort. On top of this, GTM provides increased flexibility and efficiency in managing your analytics implementation.

Indeed, anything Autotrack can do, GTM can do better!

The rest of this post will detail how you can replicate (and improve on) the functionality of Autotrack (as of version 0.6.2) within GTM:

1. Button Click Tracking (eventTracker)
2. Responsive Layout Tracking (mediaQueryTracker)
3. Outbound Form Tracking (outboundFormTracker)
4. Outbound Link Tracking (outboundLinkTracker)
5. Social Click Tracking (socialTracker – Part 1)
6. Social Button Tracking (socialTracker – Part 2)
7. URL Change Tracking (urlChangeTracker)

1. Button Click Tracking (eventTracker)

Tracks an event for any click on an element with a specified ID.

  1. Enable the built-in Click ID variable in GTM
    GTM Click ID Variable
  2. Create a Click Trigger to fire on your target elements, based on its id or class value. For example: {{Click ID}} contains “learn-more”
    Create a Click Trigger
  3. Create a Universal Analytics Event tag, and set it to fire on your click trigger from the previous step. Set the Click ID variable as the Event Label.
    Create a Event Tag

Notes:

  • You can follow the same process with {{Click Classes}} or another built-in Click variable that identifies the element(s) you want to track.
  • If your elements have a custom data attribute, you can retrieve its value with a custom JavaScript variable in GTM. For example, to retrieve the value of a “data-id” attribute, use the following function in a custom JavaScript variable:
     function() {
       return {{Click Element}}.getAttribute('data-id');
     }

2. Responsive Layout Tracking (mediaQueryTracker)

Detects and sets custom dimensions for Breakpoint, Resolution, and Orientation upon page load:

Note: The scripts below are inspired by the Autotrack library, developed by Philip Walton. We have refactored the code for GTM and added support for browsers that do not support matchMedia.

  1. Create Custom JavaScript variable, breakpoint:
    function() { 
      //Configure breakpoint widths here:
      var breakpoints = [
        {'width' : 'all', 'size': 'xs'},
        {'width' : '(min-width: 420px)', 'size': 'sm'},
        {'width' : '(min-width: 570px)', 'size': 'md'},
        {'width' : '(min-width: 800px)', 'size': 'lg'},
        {'width' : '(min-width: 1000px)', 'size': 'xl'}
      ];
    
      // will store the final result of comparison
      var result;
    
      // compare breakpoints to what is used
      breakpoints.forEach(function(element){
        //If browser support matchMedia, use it
        if (window.matchMedia){
         // return current media query
         if (window.matchMedia(element.width).matches) {
           result= element.size;
         } 
        } else { //matchMedia not supported, try using width values
          if (Number(element.width.replace( /\D/ig, '')) < document.documentElement.clientWidth){
            result= element.size;
          }
        }
      });
    
      return result;
    }
    
  2. Create Custom JavaScript variable, resolution:
    function () {
        //Configure resolutions here, will return value of ratio:
        var resolutions = [
            {'resolution': 'all', 'ratio': 1},
            {'resolution': '(min-resolution: 144dpi)', 'ratio': 1.5},
            {'resolution': '(min-resolution: 192dpi)', 'ratio': 2}
        ];
    
        var result;
        resolutions.forEach(function (element) {
            var ratio = 1;
            //If browser support matchMedia, use it
            if (window.matchMedia) {
                // return current media query
                if (window.matchMedia(element.resolution).matches) {
                    result = element.ratio;
                }
            } else { //matchMedia not supported
                if (window.screen.systemXDPI !== undefined 
                    && window.screen.logicalXDPI !== undefined 
                    && window.screen.systemXDPI > window.screen.logicalXDPI) {
                    // Only allow for values > 1
                    ratio = window.screen.systemXDPI / window.screen.logicalXDPI;
                } else if (window.devicePixelRatio !== undefined) {
                    ratio = window.devicePixelRatio;
                }
                if (element.ratio === (Math.round(ratio * 100) / 100)) {
                    result = element.ratio;
                }
            }
        });
        return result + 'x';
    }
    
  3. Create Custom JavaScript variable, orientation
    function() { 
      //If browser support matchMedia, use it
      if (window.matchMedia){
        if (window.matchMedia('(orientation: landscape)').matches) {
         return 'landscape';
        } else if (window.matchMedia('(orientation: portrait)').matches) {
          return 'portrait';
        }
      } else { //matchMedia not supported, use screen height and width instead
        if (window.screen.width < window.screen.height){
          return 'portrait';
        } else {
          return 'landscape';
        }
      }
    }
    
  4. Create custom dimensions in GA for Breakpoint, Resolution, and Orientation. Select scope as “Hit”. Note the index value for each dimension.
    Create a Custom Dimension for Breakpoint
  5. In GTM, configure the custom dimensions in your base GA pageview tag, matching the dimension index values from GA.
    Configure Breakpoint Custom Dimensions

3. Outbound Form Tracking (outboundFormTracker)

Tracks an event when a form submits to an external domain:

  1. Create a Form Submission trigger. Fire when {{Form URL}} does not match the domain of your site.
    Create a Form Submission Trigger
  2. Create a Universal Analytics Event tag and set it to fire on your outbound form trigger. Use {{Form ID}} or another built-in Form variable to label your event.
    Create an Event Tag

4. Outbound Link Tracking (outboundLinkTracker)

Tracks an event upon click of a link to an external domain:

  1. Create a Click trigger on Just Links. Fire when {{Click URL}} does not match the domain of your site.
    Create a Click Trigger
  2. Create a Universal Analytics Event tag and set it to fire on your outbound link click trigger. Use {{Click URL}} to label your event with the outbound link destination.
    Create an Event Tag

5. Social Click Tracking (socialTracker – Part 1)

Tracks a social interaction for clicks on custom social interaction buttons.

  1. Refer to 1. Button Click Tracking for how to identify clicks on a specific element using Click ID, Click Classes, or another attribute.
  2. Create a Click trigger to fire when a social interaction click occurs:
    Create a Social Interaction Click Trigger
  3. Create a Universal Analytics tag, select Social as hit type. Enter appropriate values for Network, Action, and Target. Set it to fire on your click trigger from the previous step.
    Create a Social Tag

5. Social Button Tracking (socialTracker – Part 2)

Automatically tracks events for clicks on official Twitter “tweet” or “follow” buttons and Facebook “like” buttons.

Note: The scripts below are inspired by the Autotrack library, developed by Philip Walton. We have refactored the code to push information into the data layer.

  1. Create a Custom HTML tag
  2. Insert the following custom script:
    <script>
    /**
     * Adds event handlers for the "tweet" and "follow" events 
     * emitted by the official Twitter tweet and follow buttons.
     * Pushes info to dataLayer with 'social' event
     */
    
    try {
      twttr.ready(function() {
    
        twttr.events.bind('tweet', function(event) {
          //Ignore tweets from widgets other than tweet button.
          if (event.region != 'tweet') return;
    
          var url = event.data.url ||
                    event.target.getAttribute('data-url') ||
                    window.location.href;
    
          dataLayer.push({
            'event': 'social',
    	'socialNetwork': 'Twitter',
    	'socialAction': 'tweet',
    	'socialTarget': url
          });
        }.bind(this));
    
        twttr.events.bind('follow', function(event) {
          //Ignore follows from widgets other than follow button.
          if (event.region != 'follow') return;
    
          var screenName = event.data.screen_name ||
                    event.target.getAttribute('data-screen-name');
            
            dataLayer.push({
    	  'event': 'social',
    	  'socialNetwork': 'Twitter',
    	  'socialAction': 'follow',
    	  'socialTarget': screenName
    	});		
        }.bind(this));
    
      }.bind(this));
    } catch(e) {}
    
    /**
     * Adds event handlers for the "like" and "unlike" events 
     * emitted by the official Facebook like button. 
     * Pushes info to data layer with 'social' event
     */
    
    try {
      FB.Event.subscribe('edge.create', function(url) {      
        dataLayer.push({
          'event': 'social',
          'socialNetwork': 'Facebook',
          'socialAction': 'like',
          'socialTarget': url
        });		  
      }.bind(this));
    
      FB.Event.subscribe('edge.remove', function(url) {      
         dataLayer.push({
           'event': 'social',
           'socialNetwork': 'Facebook',
           'socialAction': 'unlike',
           'socialTarget': url
         });	  
      }.bind(this));
    } catch(e) {}
    </script>
  3. Set to fire on a Window Loaded trigger
  4. Create custom event trigger on “social” event.
  5. Create data layer variables for socialNetwork, socialAction, and socialTarget
  6. Create a Universal Analytics Social tag.
    Create a Social Tag

6. URL Change Tracking

Sends pageviews upon dynamic URL changes (including hash changes):

  1. Create a History Change trigger on All History Changes
    Create a History Change Trigger
  2. Create a custom JavaScript variable Page Query as follows:
    function() {
       return window.location.search;
    }
    
  3. Create a custom JavaScript variable Page Hash as follows:
    function() {
       return window.location.hash;
    }
    
  4. Create a Universal Analytics pageview tag, and set it to fire upon your history change trigger (Or add the history change trigger to your existing base pageview tag). Set the “page” field to {{Page Path}}{{Page Query}}{{Page Hash}}.
    Create a Pageview Tag

It should be noted, as per the Autotrack documentation, that “autotrack is maintained by the Google Analytics developer relations team and is primarily intended for a developer audience. It is not an official Google Analytics product and does not qualify for Google Analytics Premium support.

Even Autotrack developer Philip Walton says that using GTM makes sense “if anyone on your team who might need to access the analytics implementation is a non-developer” or “if you want to add non-analytics tags to your page and want to keep the configuration all in one place.”

So, unless your marketing team is run by developers, GTM is the way to go!

Are there other interactions on your website that you would like to “auto” track with Google Tag Manager? Let us know!

By |2018-03-05T13:18:50-04:00March 9th, 2016|22 Comments

22 Comments

  1. Ben McCarty March 25, 2016 at 11:29 am - Reply

    Seriously awesome tutorial on hacking Google Tag Manager to improve on Google Analytics autotrack features! Thank you!

    But for the sake of argument, let’s say you deploy your GA tracking snippet via GTM already, and you still want to enable the actual autotrack plugin. Is it possible, within a GTM standard Universal Analytics tag, to insert the line to require the plugin and the reference to the plugin’s location?

    Thanks,
    Ben

    • Marc Soares March 28, 2016 at 9:03 am - Reply

      Thanks Ben!

      The Universal Analytics template tag in GTM does not provide you with the ability to load plugins. It’s not possible to add the “require” call within the template. However, if you did want to load the autotrack plugin (or some other custom plugin), I recommend taking a look at Simo Ahava’s post here: http://www.simoahava.com/analytics/access-the-tracker-object-in-your-page-view-tag/.

      Simo explains how you can access the GA tracker object via GTM in order to get the clientId or load plugins. I can’t guarantee that this will work with all the features of the autotrack plugin, but this is the method that you would need to use to enable analytics.js plugins through GTM.

      Hope that helps,
      Marc

      • Ben McCarty March 28, 2016 at 10:15 am - Reply

        Thank you Marc! Really appreciate your time answering. Definitely a big help!

        Ben

  2. Ben Klocek March 25, 2016 at 6:22 pm - Reply

    Great work. Thank you for sharing this!

    • Marc Soares March 28, 2016 at 8:56 am - Reply

      Thanks! Hope you found it useful!

  3. Milos Milosavljevic July 2, 2016 at 4:54 am - Reply

    Thanks for the great blog.
    What would the complete setup be for tracking an angular.js single page app. How would I combine the basic GA tag and the URL Change Tracking tag, for example.

    You will see the address of the app in the website field. We are still preparing for Beta.

    • Marc Soares July 7, 2016 at 2:59 pm - Reply

      Hi Milos,

      Glad you found the post useful! If you wish to track each URL change as a pageview in GA, you would just need to configure a GA pageview tag to fire on a History Change trigger. In step 6d. in the post, I show how you can configure the page path of the GA tag to capture the hash portion of the URL.

      Hope that answers your question. If you would like further assistance with tracking your app using GA/GTM, please give us your permission to contact you via email.

      Thanks,
      Marc

  4. Oren July 26, 2016 at 9:55 am - Reply

    Hi I love this post. Could you update or follow up how to support new release with additional plugins.

  5. Paul September 15, 2016 at 10:34 am - Reply

    Amazing post. Not quite working for me yet.

    I am implementing 6. URL Change Tracking.

    In preview mode I see that the event is firing after each change in url, so that’s working great, however, it is not being tracked as a page view in the analytics dashboard. Does this make sense? It should be tracked as a page view the way it is set up, no?

    • Paul September 15, 2016 at 10:37 am - Reply

      Perhaps it will not show up in the Real time data as a page view, although i would have thought it would. Do you have any idea on this?

    • Marc Soares September 15, 2016 at 4:57 pm - Reply

      Hi Paul. Did you implement a Google Analytics pageview tag as described in step 6d? If you have configured this tag to fire on the URL change trigger, you should see the pageview appear in GA, even in the Real-Time reports.

      • Paul September 16, 2016 at 3:25 am - Reply

        I have set it up exactly as described, but I am not seeing these as page views in the live reports. How strange!

        • Paul September 16, 2016 at 5:07 am - Reply

          if possible would you mind if I contacted you by email to provide more detail?

          • Paul September 16, 2016 at 6:12 am - Reply

            Got it working. Works a charm, thanks!

  6. Eric Melounou April 13, 2017 at 6:32 am - Reply

    Hi, and thanks for your help.

    just a remark about this method, I’ve noticed that this method doesn’t work for all browsers as it uses the popstate history management. is it right that it doesnt work with firefox or internet explorer ?

    • Marc Soares April 13, 2017 at 10:21 am - Reply

      Hi Eric,

      I assume you are referring to the URL Change Tracking, which uses the History Change listener in GTM.

      The methods used by this trigger are cross-browser compatible. You may encounter issues in IE9 and below, but otherwise it should work in most recent browsers.

      Have you encountered any specific issues with this method in Firefox or IE?

  7. Sion June 7, 2017 at 7:24 pm - Reply

    Hi Eric,

    Thanks for the guide. It’s really clearly explained.

    I just have a question relating to (6) –

    I share the same GTM GA tag between my marketing (top level domain) and webapp site (sub-domain).

    I currently have an All Pages trigger firing the GA tag, but I’m not 100% clear from your instructions if I should add the History Change trigger in addition to my All Pages trigger in the one GA tag, or do separate tags, or add rules to my triggers so that All Pages only fires on the marketing site and History Change only fires on the webapp site?

    Thanks for your help!

    • Marc Soares June 8, 2017 at 3:02 pm - Reply

      Hi Sion,

      I suggest using separate GA tags for your marketing site and web-app. The marketing site tag can fire upon pageview and the web-app tag can fire upon history change. This will require you to add additional conditions to your triggers to match the domain/subdomain.

      As the history change tracking requires setting the “page” field to include the URL hash, it’s best to do this only where it’s needed, i.e on the web-app site.

      Hope that helps!

      • Sion June 8, 2017 at 4:39 pm - Reply

        Thanks Marc!

        That seems to be working fine 🙂

        There is a warning about ‘Ignoring create request for duplicate tracker name’, but I guess that’s fine right?

        Sion

        • Marc Soares June 16, 2017 at 10:02 am - Reply

          Hi Sion,

          I don’t think I have seen that warning before. But if GTM is ignoring the duplicate request, then everything should be fine. Just make sure that you are not seeing duplicate pageviews.

          Marc

          • Sion June 25, 2017 at 12:44 am - Reply

            Thanks Marc!

  8. Michael van Laar June 22, 2017 at 5:55 am - Reply

    Would be interesting if anyone has tried building a GTM equivalent to Autotrack’s impressionTracker plugin (https://github.com/googleanalytics/autotrack/blob/master/docs/plugins/impression-tracker.md) or maxScrollTracker plugin (https://github.com/googleanalytics/autotrack/blob/master/docs/plugins/max-scroll-tracker.md).

Leave A Comment