Skip to content

Instantly share code, notes, and snippets.

@timelf123
Created September 24, 2014 19:31
Show Gist options
  • Save timelf123/b88b4567486cbaaa0b99 to your computer and use it in GitHub Desktop.
Save timelf123/b88b4567486cbaaa0b99 to your computer and use it in GitHub Desktop.
Google Analytics Automatically Track Outbound Links
function _gaLt(event){
var el = event.srcElement || event.target;
/* Loop up the tree through parent elements if clicked element is not a link (eg: an image inside a link) */
while(el && (typeof el.tagName == 'undefined' || el.tagName.toLowerCase() != 'a' || !el.href))
el = el.parentNode;
if(el && el.href){
if(el.href.indexOf(location.host) == -1){ /* external link */
ga("send", "event", "Outgoing Links", el.href, document.location.pathname + document.location.search);
/* if target not set then delay opening of window by 0.5s to allow tracking */
if(!el.target || el.target.match(/^_(self|parent|top)$/i)){
setTimeout(function(){
document.location.href = el.href;
}.bind(el),500);
/* Prevent standard click */
event.preventDefault ? event.preventDefault() : event.returnValue = !1;
}
}
}
}
/* Attach the event to all clicks in the document after page has loaded */
var w = window;
w.addEventListener ? w.addEventListener("load",function(){document.body.addEventListener("click",_gaLt,!1)},!1)
: w.attachEvent && w.attachEvent("onload",function(){document.body.attachEvent("onclick",_gaLt)});
@timelf123
Copy link
Author

The best method of "auto-tracking" outgoing links is to automatically detect outbound links with JavaScript when they are clicked, and automatically track that event. That tracking event should first check to see whether that link is destined to open in a new window (target="_blank"), and:

If yes, register the track, and open the link in the new window
If no, register the track and delay opening the link by half a second, then proceed to open that link.
This method is by far the most robust, and simply means you need to include an external JavaScript file on your pages.

@timelf123
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment