Google Analytics, Ghostery, Ad Blockers, And Event Tracking

masterjosh
by
masterjosh
Apr 04, 2019
Google Analytics, Ghostery, Ad Blockers, And Event Tracking

Most of us website owners and webmasters use Google Analytics to track visitor interaction on our websites. It provides us a wealth of information on stuff like pageviews, session counts, bounce rates, what people click, etc. This data can help us make important business decisions, like whether to remove a feature or when to schedule a maintenance.

However, not everyone is comfortable with Google Analytics tracking or even any form of third-party tracking scripts. Concerned about their privacy, some people are now taking extra steps to protect their themselves. Some of these privacy and anti-tracking steps include:

  • Installing ad blockers (which also blocks Google Analytics sometimes).
  • Using privacy browsers with tracking protection (like the Firefox Focus browser which is currently available for mobile). The last time I performed testing with Firefox Focus, I noticed that it always totally blocked Google Analytics tracking as well as Adsense and Media.net ads.
  • Using a plethora of other privacy-focused tools like Ghostery and others.
  • Enabling tracking protection in Firefox.

I support the idea of privacy protection on the web. And while I think it is great to see people concerned about their privacy and taking extra steps to protect themselves, the problem is that blocking trackers like Google Analytics may sometimes break other things.

When Anti-Tracking Tools Break Sites

When third-party tracking scripts like Google Analytics are intentionally blocked by tools like Ghostery, some critical piece of website functionality may break. This happens when some of the website code depends on the third-party script and the script is not there.

A common example of this problem is when we use Google Analytics to track external (or outbound) links.

Let’s first review how this is generally set up (as recommended by Google) and investigate the problem that occurs when users block Google Analytics. Thereafter, we will discuss a technique that webmasters can use to avoid the problem.

In this demo, I will be working with the analytics.js tracking code and not the legacy (ga.js) version. Note, however, that there is currently an even more recent Google Analytics script version. It is called the global site tag (gtag.js)

As of this writing (December 2, 2018), I think analytics.js is still the most popular version of Google Analytics (though I couldn’t find any official stats). I still use it on many of the sites I manage and haven’t seen any major reasons to migrate to the newer version. I assume most other webmasters use it too so I decided to focus on it here. In principle however, even though the actual code is different for analytics.jsversus gtag.js, the solution described below should be easily extended to gtag.js as well.

Google’s Recommended Method Of Tracking Outbound Links (And Its Potential Problem)

Google’s recommended method of tracking outbound links with the analytics.js script can be found here.

Here’s what they recommend…

After adding the regular analytics.js tracking code to you site header, you also need to add this extra code to your header if you want to track external links:


<script>
var trackOutboundLink = function(url) {
   ga('send', 'event', 'outbound', 'click', url, {
     'transport': 'beacon',
     'hitCallback': function(){document.location = url;}
   });
}
</script>

And you will need to code each external link you want to track to include the onclick attribute like this:


<a href="https://masterjosh.me">Check out masterjosh.me</a>

Now, your outbound clicks will appear in your Analytics Events reports with a Category of “outbound” and an Action of “click”.

Here’s what this code means:

  • The “return false” added to the onclick attribute means that when a user clicks on the link at first, they are not immediately taken off the page.
  • When a user clicks the link, the click is added to Google Analytics’ queue of events to track. And Google Analytics is instructed to take the user to the new page AFTER the click has been added to the queue.
  • Google Analytics now processes the event.
  • After processing the click, Google Analytics triggers “hitCallback” which finally takes the user to the external page they originally clicked.

This sequence ensures that the user does not leave your website before their action is recorded by Google Analytics.

The problem is that, since the above method relies on Google Analytics to send the user to the requested page, if the user has blocked Google Analytics using Ghostery or an ad blocker, the Google Analytics code will never get executed. The event never gets processed. And all outbound links that you’re tracking with Google Analytics will be broken and non-functional.

This becomes a problem for both the website owner as well as for the user browsing the website. It is terrible and frustrating user experience.

How To Check If Google Analytics Is Loaded

Before discussing how to avoid the above problem, I want to first share the code I use to detect if Google Analytics has been loaded (since some of my developer readers may only be interested in the logic I use for that). There are quite a few suggestions on how to do this but the method I use below is one I have personally tested extensively. It combines 3 different checks.

The cool thing about this technique is that depending on how the ad blocker or anti-tracking script works, one or two of the checks in our OR condition may fail. But from my extensive testing across different ad blockers and privacy tools, I haven’t as yet encountered a scenario where all three checks failed. So, simply put, if your user is blocking Google Analytics, this block of code will detect it.

Here goes…


var ehi_ga = window[window['GoogleAnalyticsObject'] || 'ga'];
if(typeof ehi_ga != 'function' ||  ehi_ga.loaded != true || !ehi_ga.create)
{
    // Google Analytics is NOT loaded
}
else
{
    // Google Analytics IS loaded
}

Now we can avoid the outbound tracking issue described above by modifying the event tracking script to detect whether or not Google Analytics is loaded.

Modifying The Outbound Tracking Code To Check For Google Analytics

The regular analytics.js tracking code looks like this:


<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-XXXXXXXX-X', 'auto');
  ga('send', 'pageview');
</script>

This code is added to all your pages whether you’re also using the event tracking script or not. It creates a global ga object which becomes available in JavaScript whether the rest of the script was successfully loaded or not. This means that we can add events to the queue even before Google Analytics has loaded. This is really cool for tracking events that happen really quickly.

Let’s now go ahead and tweak the event tracking script to detect if Google Analytics was loaded.


<script>
    var trackOutboundLink = function(url)
    {
        var ehi_ga = window[window['GoogleAnalyticsObject'] || 'ga'];
        if(typeof ehi_ga != 'function' ||  ehi_ga.loaded != true || !ehi_ga.create)
        {
            // Google Analytics is NOT loaded. We will follow the link by ourselves.
            document.location = url;
        }
        else
        {
            // Google Analytics IS loaded. So we can rely on it to follow the link.
            ga('send', 'event', 'outbound', 'click', url, {
                'transport': 'beacon',
                'hitCallback': function(){document.location = url;}
            });
        }
    }
</script>

Now, for users who block Google Analytics, your links will continue to work. You just won’t have any data tracked for those users.

As mentioned above, this technique can be tweaked for use with the new gtag.js(global site tag). It can even be changed to work with other third-party tracking scripts like Kissmetrics and Mixpanel. They all get blocked by anti-privacy scripts and ad blockers.

Including a fallback (as above) for any script that is not coming from your own domain is always a good web development practice.




Add Comment