Last active
September 15, 2020 12:52
-
-
Save leighmcculloch/7596803 to your computer and use it in GitHub Desktop.
This JavaScript will catch any outbound links and register them with Google Analytics before the browser loads the linked URL. This script works with Google's new analytics.js and not the older ga.js. This script ensures the attempt to register the page with Google Analytics is complete before continuing to load the next page. This capability is…
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
/* Google - Standard new analytics code. Replace the UA-XXXXXXXX-X and example.com. */ | |
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ | |
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), | |
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) | |
})(window,document,'script','http://www.google-analytics.com/analytics.js','ga'); | |
ga('create', 'UA-XXXXXXXX-X', 'example.com'); | |
ga('send', 'pageview'); | |
/* Catch any outbound links, register them with Google Analytics. | |
Outbound links will be displayed in your analytics account as 'out/[outbound url]'. | |
Copyright (c) 2013, Leigh McCulloch | |
All Rights Reserved | |
License: BSD-2-Clause (http://opensource.org/licenses/BSD-2-Clause) */ | |
$(function(){ | |
$('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