问题
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'shitCallback
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