codeman
codeman

Reputation: 9028

Unable to create custom page tracking URL for external links with Universal Analytics Code

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?

Upvotes: 1

Views: 413

Answers (1)

Scott Jungwirth
Scott Jungwirth

Reputation: 6675

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:

onclick="trackAndRedirect(); return false;"

<script>
function trackAndRedirect() {
  ga('send', 'pageview', {
    'page': '/myexternalpage',
    'title': 'External Page',
    'hitCallback': function() {
      //alert('analytics.js done sending data');
      document.location = "http://www.externalsite.com";
    }
  });
}
</script>

https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#hitCallback

Upvotes: 1

Related Questions