Track external link clicks with Google Universal Analytics
Google Analytics and the newer Univeral Analytics are useful ways of keeping track of how users interact with your site. If you want to track which external links are clicked, there are several methods. Although Google Analytics does not do this by defaults, you can do so with custom events.
Try using this snippet with your pages:
/**
* Hook external links to feed data to Google Analytics.
*/
(function () {
/* Check we have access to `querySelectorAll` and the
* GA object. This means this code won't run on all
* browsers.
*/
if (!Element.prototype.querySelectorAll ||
typeof ga === "undefined") {
return;
}
/* `click` event handler to push the event to GA */
var handler = function(e) {
var self = this;
/* Track the event using universal analytics.
* The old GA call would look like:
*
* _gaq.push(
* ['_trackEvent',
* "External Link",
* this.href.replace(/^http[s]?:\/\//, '')
* ]);
*/
ga('send',
'event',
'External Link',
'click',
this.href.replace(/^http[s]?:\/\//, ''));
/* If the link opens in the same window, we need a
* delay to allow the request to go back to GA.
*/
if ("_blank" != this.target) {
if (Event.prototype.preventDefault) {
e.preventDefault();
}
setTimeout(function() {
document.location.href = self.href;
}, 100);
return false;
}
}
/* Find all external links and add the handler. This
* code won't work with IE < 9.
*/
var links = document.querySelectorAll('.external-link');
for (var i = links.length - 1; i >= 0; i--) {
if (Element.prototype.addEventListener) {
links[i].addEventListener('click', handler);
}
else if (Element.prototype.attachEvent) {
links[i].attachEvent('onclick', handler);
}
}
})();
Make sure it comes after the snippet used to load GA.
Read more
For further information see: