Outbound link click custom JavaScript variable for Google Tag Manager

Track outbound link clicks in Google Tag Manager without customising for every domain with this custom JavaScript variable.

Why would you need this?

When people go to different websites from links in your website, you want to know where they’re going. You can manually tag certain outbound links using JavaScript or Google Tag Manager, but this is time consuming and adds unneccessary bulk to your analytics implementation.

The variable in this post allows you to check whether each outbound link click contains the top level domain from the current page, and returns true if it doesn’t. You can then use this to create your link click triggers in Google Tag Manager.

The custom JavaScript variable

The custom JavaScript variable allows you to programatically create variables using JavaScript. All you need to do is create an anonymous function which returns a value, like below. In this case, it will return the string ‘somethingElse1’ on every dataLayer event.

    var something = "somethingElse" + "1";
    return something

Once you’ve saved this and activated preview mode (make sure you refresh it if it’s already active) you’ll be able to see the value of this variable for each dataLayer event in Google Tag Manager.

There are a significant number of use cases for this variable and the outbound link click checker is one of them.

The solution

Before you implement this, you need to enable the built in click URL variable.

The solution is based on this stack overflow thread. Make sure you use the link clicks only trigger in Google Tag Manager, to ensure it doesn’t fire on unintended elements. You can use ‘wait for tags’ in your trigger as long as you’ve tested it thoroughly on every page.

  var i,h,
    hostname = document.location.hostname.split('.');
  for(i=hostname.length-1; i>=0; i--) {
    h = hostname.slice(i).join('.');
    document.cookie = weird_cookie + ';domain=.' + h + ';';
      document.cookie = weird_cookie.split('=')[0] + '=;domain=.' + h + ';expires=Thu, 01 Jan 1970 00:00:01 GMT;';
  var regex = new RegExp(h);
  if (regex.test({{Click URL}})){
    return false
  else return true;

Implementing the variable in a trigger and tag

To use this tag, implement a ‘Link Click’ trigger where your outbound link click variable equals true.

You can then attach this trigger to a tag, like a Google Analytics event tag.

This one tag can be used to create a whole lot of different outbound link click goals, like clicks to your Facebook page, LinkedIn page or directory listing.

Final thoughts

Please test this thoroughly before implementing, especially if using wait for tags on a single page application. If you catch any edge cases, let me know in the comments.


There are no comments on this entry.