简体   繁体   中英

Google Analytics Event Tracking - Not working for a download link

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM