I'm using the following Universal Analytics code on all of the pages on my site:
<script>
(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','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXX-XX', 'mydomain.edu');
ga('send', 'pageview');
</script>
On some of the external links, I need to be able to track these. So I tried adding onclick code like this:
<a href="http://www.externalsite.com" onclick="ga('send', 'pageview', {'page': '/myexternalpage','title': 'External Page'});">External page</a>
However, when I watch real-time Analytics, it doesn't seem to be recognizing these.
Any ideas?
This is a race condition caused by the track request not completing before the browser starts to load the external link.
What you need to do is use the hitCallback parameter, and prevent the link from navigating by using
return false
in the click handler:https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#hitCallback