Forked from leighmcculloch/Google Analytics.js Outbound Link Tracking.js
Last active
May 4, 2017 21:33
-
-
Save devinrhode2/48e54fc771def2d7a9d264f4f2b5b5da to your computer and use it in GitHub Desktop.
catch any outbound links
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
$('a:not([href*="' + document.domain + '"])').click(function(event){ | |
/* get all the info from the link */ | |
var anchor = $(this); | |
var href = anchor.attr('href'); | |
/* check that the link isn't a relative link */ | |
var hrefLead = href.charAt(0); | |
if (hrefLead != '.' && hrefLead != '#' && hrefLead != '/') { | |
/* stop the browser redirecting away, we'll do it manually after the hit is registered with Google */ | |
event.preventDefault(); | |
/* strip the protocol, because it's wasted space */ | |
var hrefNoProtocol = href.replace(/http[s]?:\/\//, ''); | |
ga('send', 'pageview', { | |
/* register the outgoing link as '/out/[outgoing link]' */ | |
'page': 'out/'+hrefNoProtocol, | |
/* only when we've finished registering the link click, send the user to the link they clicked on */ | |
'hitCallback': function() { | |
document.location = href; | |
} | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment