Bug related to intercepting clicks for Google Analytics Event tracking

I’ve been using Google Analytics for a number of projects to track usage. To do useful things beyond tracking pageviews you can use javascript to track activity on the page and send these “Events” to Google Analytics. Events are useful for tracking things like clicks on links. The solution to tracking link clicks is to add a listener on click events and then prevent the default behavior, send the event data to Google Analytics, and then send the browser window on its way to the clicked URL.

Something like this:

$(document).on('click', function(e) {
    
    // Send the data to GA
    ga('send', 'event', {
        'hitType': 'event',
        'eventCategory': category,
        'eventAction': action,
        'eventLabel': label,
        'hitCallback': function () {
            // Once send is complete
            // send the browser on its way
            document.location = link;
        }
    });

    // Don't follow the link
    e.preventDefault();

    // in case something goes wrong
    // and the callback doesn't fire
    // send the browser on its way anyway
    setTimeout(function() {
      document.location.href = link.href;
    }, 200);

}

For details about how to do this you should start with Google’s documentation.

The reason we prevent the default behavior is to make sure the data actually gets sent to Google before the browser moves on to the next page. There is, however, a catch to doing this. It breaks a browser shortcut that I (and I would assume others) find useful.

I generally use Chrome on OS X. If I want to open a link in a new tab I hold down the command key and click on the left mouse button. On Ubuntu and Windows the equivalent is ctrl-click. Well, if the link behavior has been overridden by preventDefault() this doesn’t work and the link just opens, stupidly, in the same window as the current page. Ugh. It’s a minor inconvenience for maybe a small number of people, but it’s annoying, makes your website seem broken, and there’s an easy fix.

It turns out you can detect key presses with javascript.

if (e.metaKey || e.ctrlKey) {
    ga(...)
    return;
} else {
    ga(...)
    e.preventDefault();
}

By detecting the pressed modifier keys you can decide whether or not it’s appropriate to use preventDefault(). If the link will open in a new window you don’t really need to override the link opening because the current page will remain and have plenty of time to send the Event data on to Google.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>