Created
May 27, 2016 03:31
-
-
Save akngs/362117239656b38d184017a379457323 to your computer and use it in GitHub Desktop.
GA external link tracker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Place this code just before the closing body tag: </body> | |
(function() { try { | |
var host = location.href.match(/^https?:\/\/([^\/]+)/i)[1]; | |
// Find all links in current document | |
var links = document.getElementsByTagName('a'); | |
// Register click handlers to external links | |
for(var i = 0; i < links.length; i++) { | |
var href = links[i].href; | |
var isExternal = | |
!href.match(/^javascript\:/i) && | |
href.replace(/^https?:\/\//i, '').indexOf(host) !== 0 && | |
href.match(/^https?:\/\//i); | |
if(isExternal) { | |
if(links[i].addEventListener) { | |
links[i].addEventListener('click', clickHandler); | |
} else { | |
links[i].attachEvent('onclick', clickHandler); | |
} | |
} | |
} | |
function clickHandler(e) { | |
var source = e.srcElement || e.target; | |
var href = source.href; | |
var newWindow = | |
(source.target && !source.target.match(/^_(self|parent|top)$/i)) || | |
e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.ctrlKey; | |
if(newWindow) { | |
// For the link opens in new window, call GA without hit callback. | |
ga('send', 'event', { | |
eventCategory: 'outbound', | |
eventAction: 'click', | |
eventLabel: href | |
}); | |
return true; | |
} else { | |
// For the link opens in current window, prevent click event and use hit callback. | |
ga('send', 'event', { | |
eventCategory: 'outbound', | |
eventAction: 'click', | |
eventLabel: href, | |
hitCallback: function() {location.href = href;} | |
}); | |
e.preventDefault && e.preventDefault(); | |
return false; | |
} | |
} | |
} catch(e) {} })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment