Google Analytics Event Tracking - Not working for a download link

醉酒当歌 提交于 2019-12-24 18:51:56

问题


I just finished working on a plugin for Sketch and I created a simple landing page for users to download the plugin. I want to use Google Analytics event tracking to track the downloads, but the event tracking is not working and I can't seem to figure out why.

Here is what the link looks like:

<a href="downloads/colorspark.zip" download onClick="ga('send', 'event', 'Downloads', 'download', 'ColorSpark for Sketch');">Download</a>

Does anyone see what I'm doing wrong? Do I need to add any other code anywhere else besides the onclick attribute?


回答1:


My bet is that you're facing what we call a race condition: the moment the user clicks the link, the browser initiates a page change, thus GA is interrupted before it's had a chance to send the event.

2 options

  • Open link in new tab: add target="_blank" to your links so they open in a new tab and don't interrupt GA in the current tab.
  • Prevent Default + Hitcallback: you can use a custom function for onClick that will prevent the link from opening by default (return false;), trigger the GA event, and use GA's hitCallback to trigger the page change programatically.

For option 2 there are different ways of doing it (since it's custom code). Here is an example from Google: https://support.google.com/analytics/answer/1136920?hl=en

<script>
/**
* Function that tracks a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label. Setting the transport method to 'beacon' lets the hit be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var trackOutboundLink = function(url) {
   ga('send', 'event', 'outbound', 'click', url, {
     'transport': 'beacon',
     'hitCallback': function(){document.location = url;}
   });
}
</script>
You'll also need to add (or modify) the onclick attribute to your links. Use this example as a model for your own links:

<a href="http://www.example.com" onclick="trackOutboundLink('http://www.example.com'); return false;">Check out example.com</a>


来源:https://stackoverflow.com/questions/51294112/google-analytics-event-tracking-not-working-for-a-download-link

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