Posterous theme by Cory Watilo

Auto-track outgoing links with Google Analytics

Google Analytics Help does not track outgoing links unless you embed onclick handlers in every link.  This seemed repetitive, so here’s what I came up with to automatically listen for outgoing click events and send them to GA.

This code is written for jQuery and Ruby on Rails, but can be adapted for your purpose.

$(function() {
  $('a[href^=http]').click(function() {
    var link = $(this).attr('href');
    if(pageTracker && 0 > link.indexOf('<%= request.domain %>')) {
      pageTracker._trackPageview('/outgoing/' + link.replace(/https?:\/\/([^\?]*).*/i, '$1'));
    }
  })
});

Things to note:

  • jQuery attribute selector [href=^http] filters only absolute links
  • pageTracker existence check is for development mode where Google Analytics is disabled (in my case)
  • Replace regular expression captures “domain/path” of the link without the query string.  Modify according to your needs.