Unable to create custom page tracking URL for exte

2019-07-28 23:34发布

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?

1条回答
何必那么认真
2楼-- · 2019-07-29 00:05

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

查看更多
登录 后发表回答