Google Analytics is great, and keeps improving all the time. But one thing it can’t do natively is track where a visitor goes after leaving your site through an external link.
You can, of course track this yourself, by firing off an AJAX call to store data when a user clicks an external link.
There’s an easier way though, one that ties into your existing data in Google Analytics. It leverages “event tracking”.
Google Analytics provides a means to track custom events on your site, such as “user downloaded a PDF” or “user clicked a radio button”.
In our case, we’re interested in tracking when a user clicks an external link from your website.
Let’s say, for example, that you have some Amazon affiliate links setup on your site. You’d like to know which specific pages links your visitors are using.
Let’s start with the code, then I’ll explain. jQuery example below:
$('a[href*="amazon"]').click(function(e) {
e.preventDefault(); // cancel the link event
var href = $(this).attr('href');
var label = '';
if ($(this).children('img').length) {
// use the image alt tag as the event label
label = $(this).children('img').first().attr('alt');
}
else {
// if it's a text link, use the link text as the event label
label = $(this).text();
}
var eventParams = {
'hitType': 'event',
'eventCategory': 'Amazon Link',
'eventAction': 'click',
'eventLabel': label,
nonInteraction: true
}
eventParams['hitCallback'] = function() {
location.href = href;
}
setTimeout(function() {
/* I like to add a fallback, just in case the event tracking takes too long,
or errors for some reason */
location.href = href; // in case event tracking fails
}, 2000);
ga('send', eventParams);
});
In the snippet above, we are adding a click event handler to all outbound links to Amazon.com.
The tracking on the individual links is handled automatically by grabbing the alt tag from an image or the text with a text-based link. Given this, you’ll want to make sure that your links or alt tags contain text that is easily identifiable and unique.
In order to ensure that the event tracking works, you need to “cancel” the link event itself. Google Analytics Event tracking provides a callback that you can leverage to navigate to the link “manually”.
I like to provide a “just-in-case” timeout that will be called in the off chance that Google’s callback doesn’t fire, or simply takes too long.
That’s it! You’ll find these events in the Real-Time or Behavior / Events areas of Google Analytics.