Tracking a download button click with Analytics using events

狂风中的少年 提交于 2019-12-19 06:24:10

问题


I'm tracking the Download button click on a website featuring a project of mine with this code:

function trackDownload(link) {
    try {
        _gaq.push(['_trackEvent', 'Downloads', 'Click', 'Setup executable']);
        setTimeout('document.location = "' + link.href + '"', 100);
    } catch (err) {}
    return false;
}

And the button is something as:

<a href="files/setup.exe" onclick="return trackDownload(this);">Download</a>

So, when a user clicks it, an event is pushed to Analytics and then the user is redirected to the file.

This is applicable also on external link tracking, no differences.

And now my question. Can I be sure that the Analytics event is "processed" before the user is redirect? If not, that redirection cause the event to be lost? Currently events are being tracked, but I cannot be sure that all of them are.

I read I can also try something a little bit different, pushing the redirection function into Analytics queue:

_gaq.push(function() { document.location = link.href; });

But it's not clear if this works or if it's just equivalent to the previous one. In fact, here it's said that "calls to _gaq.push [...] executes commands as they are pushed".


回答1:


You are correct in that you can push functions onto the analytics queue. Since functions or tracking events are executed/evaluated in the order that you pushed them on to the array, you should be able to do this:

function trackDownload(link) {
    _gaq.push(['_trackEvent', 'Downloads', 'Click', 'Setup executable']);
    _gaq.push(function() { document.location = link.href });
    return false;
}

Note that the try/catch isn't necessary since push() isn't documented to throw anything (and I'd recommend removing it since empty catch blocks can mask other problems).

You ask:

But it's not clear if this works or if it's just equivalent to the previous one.

In your first example (push, setTimeout), the event will be lost if Analytics hasn't finished loading when you do the redirect (because at that time, _gaq is just an array). In the version with the push(function..., then the event will be recorded before the redirect regardless of whether Analytics has finished loading at the time the user hits the download button. For this reason, I would recommend using push(function....

Be warned that the push(function... version will wait for analytics to finish loading before the redirect happens (which sounds like what you want anyway), but you may want to add a way to handle the case where analytics doesn't load.



来源:https://stackoverflow.com/questions/8481176/tracking-a-download-button-click-with-analytics-using-events

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