Outbound link tracking with the Google Analytics Universal Code using “hitCallback”

Outbound link tracking with the Google Analytics Universal Code using “hitCallback”
Rate This Post

A while ago I posted a solution that used JS functions to override JS events to post an event to an Analytics package. Recently, I found out there is a more solid out-of-box solution available for GA Universal package to efficiently ensure that events are being tracked properly – even on links/actions that redirect you within the same browser window/tab.

The previous post on the topic (at heart) is still valid, but for GA users using the Universal code I strongly suggest using this new solution because using the “hitCallback” feature waits for the GA tracker to send the data, then it fires a JS function callback once this is completed. There is no need for timeouts – as soon as GA returns you can immediately get to work.

I’m not going to exhaustively cover all the scenarios where this could be used (e.g. form submission or other variations of links tracking), but I just wanted to highlight that this function actually exists. For me it is a game-changer in the way I implement my events.

  1. <a onclick="return trackOutboundLink(this, 'Outbound Link', 'click');" target="_blank" href="http://google.ca">Google.ca</a>
  1. <script>
  2. trackOutboundLink = function(alink, cat, a) {
  3. ga('send', 'event', cat, a, alink.href, {'hitCallback':
  4. function () {
  5. //Do whatever you need to when the GA call is finished executing!
  6. document.location = alink.href;
  7. }
  8. });
  9. return false;
  10. }
  11. </script>

Reference: https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#hitCallback