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

自古美人都是妖i 提交于 2019-12-11 08:39:55

问题


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:


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



来源:https://stackoverflow.com/questions/18537577/unable-to-create-custom-page-tracking-url-for-external-links-with-universal-anal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!