Google

Tracking outbound links with Google Analytics

I’ve been looking for online tools, tutorials that could help me tracking all outbound links from my website.
I tried almost everything I found online, really, signed up for useless tool, tried dozen of JS script, but at the end I found the answer in the Google Analytics official support pages, but I still had to do some customization: the original code provided by Google Analytics works, no discussion, but I wanted to keep the “_blank” attribute somehow, and that’s why I had to edit a bit the script, and here is the final version:

<script>
/**
* Function that tracks a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label. Setting the transport method to 'beacon' lets the hit be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var trackOutboundLink = function(url) {
   ga('send', 'event', 'outbound', 'click', url, {
     'transport': 'beacon',
     'hitCallback': function(){window.open(url, '_blank');}
   });
}
 </script>

You have then to update your links as per example here below:

<a href="http://www.example.com" 
onclick="trackOutboundLink('http://www.example.com'); return false;">Check out example.com</a>

Was it useful for you? Let me know!