Wednesday, June 4, 2014

Google Analytics download events using callbacks

Debugging analytics locally

Google Analytics won't send events when testing on localhost. To enable debugging on localhost, run this command in the browser console:

_gaq.push(['_setDomainName', 'none']);

Via Stack Overflow.

Tracking downloads

A download will cancel other HTTP requests, so analytics requests won't work. You need to delay the download until the analytics event has happened.

The trick is to run a callback after the event has been sent. Using ga.js-style analytics, here is how you do it:

if (window._gaq) {
    _gaq.push(
        ["_set", "hitCallback", triggerTrackedClick],
        ["_trackEvent", "download", "click", label],
        ["_set", "hitCallback", null]
    );
} else {
    // Trigger tracked click immediately if analytics not loaded
    triggerTrackedClick();
}

Update 3 July 2015: An easier way to do this for downloads, is to target the download at either _blank or an internal iframe. Targeting the download means that the download doesn't unload the current page, so Google Analytics events aren't interrupted by the download. See this PR for an example of how the code can be simplified.