How to track traffic exiting your site

Illustration for How to track traffic exiting your site

Written by Marc on 20.01.2010

Thanks to the great work Google have been putting in, we can now gather an enormous amount of information about our site visitors for free using Google Analytics. One of the metrics that I have always been curious about is the ‘Exit Page’. Sadly, all visitors do eventually leave our sites and this metric shows what was the last page they viewed before leaving. Even more sadly, that’s as far as we can get with a basic Google Analytics deployment. Wouldn’t it be great if we could see where our visitors went after leaving our site?

Well, with a little bit of javascript magic we can.

What you’ll need on your site

  • Google Analytics (I’m using the new Asynchronous Tracking code but with a little modification it’ll work with the standard tracking code)
  • jQuery (again with some modification this can be done without, but you’re all using jQuery anyway right?)

How do we do it

We’re going to be using the Event Tracking functionality of Google Analytics to track whenever someone follows an external link on our site. Firstly we need a way of determining which links are actually external. We could add additional classes to any links you want to track or we can use a little jQuery tickery to determine that automatically.

Haven’t used jQuery before? Don’t know what on earth the $() function is? Check out the getting started guide, you’ll thank me later

1
2
3
4
$.expr[':'].external = function(obj){
  return !obj.href.match(/^mailto:/)
    && (obj.hostname != document.location.hostname);
};
jQuery Howto

This adds the :external filter allowing us to use $('a:external') to select external links.

All we need to do now is to use this selector to track events when these links are clicked. The documentation shows that the _trackEvent() method takes four parameters; Category, Action, Label and Value. Of these four, only the Category and Action are mandatory. We’ll be using the optional Label parameter to pass the URL of the external site back to Google Analytics.

1
2
3
$('a:external').click(function(){
  _gaq.push(['_trackEvent','Outbound','Link',$(this).attr('href')]);
});

Taking it further

We’re using a Category of ‘Outbound’, as these events are all related to off-site events, and an Action of ‘Link’ as we’re looking at links. We can expand on this using a little more jQuery to change this Action based on some conditions, for example if the link is within another element, if it has a particular class or if the url contains a string.

1
2
3
4
5
6
7
8
9
$('a:external').click(function(){
  var link = $(this), type = 'Link';

  if ( link.closest('ul.comments').length == 1 ) type = 'Comment';
  if ( link.hasClass('amazon') ) type = 'Affiliate';
  if ( (/pastrami/i).test(link.attr('href') ) type = 'Tasty';

  _gaq.push(['_trackEvent','Outbound',type,link.attr('href')]);
});

You could also this technique for other similar events, that might not otherwise be tracked by Google Analytics, such as for downloads

1
2
3
4
5
6
7
8
9
// track downloads of Acrobat and ZIP files
$('a:not(:external)').filter(function() {
  return (/\.(pdf|zip)$/i).test($(this).attr('href'));
}).click(function() {
  var href = $(this).attr('href'),
      pos = href.lastIndexOf('.'),
      ext = href.substr(pos+1).toUpperCase();
  _gaq.push(['_trackEvent','Download',ext,href]);
});

All done

Once that is all in place and you’ve had some events tracked by Google Analytics you’ll be able to see the events showing up in the reports. Here’s a shot of the events shortly after the launch of the Neutron Creations site on the 19th January 2010.

So that’s it. Now you can track where your visitors are going when they eventually leave your site. If you have any improvements or other uses for this sound off about them in the comments.

Photo: lansakit
Photo of Marc, who wrote this blog post

Marc Roberts is Principal & Co-Founder at Neutron Creations, where he rules over all web development and technical direction. His favourite drink is a hazelnut latte and his favourite sandwich is a croque-monsieur. Follow him on Twitter: @marcroberts.

12 Responses

  1. Carter Gilchrist

    January 21st 2010 @ 7:38 pm #

    Hi Marc, great trick! We’re working on an app (Unbounce) to help marketers easily build and test Landing Pages. Our main focus is of course on helping users increase their conversion rate and lower the bounce rate. I’m really curious about how we can leverage GA in ways like this so thanks for the tip!

    Also, how much of a difference do you notice when using the Asynchronous Tracking snippet?

  2. Sharry

    January 22nd 2010 @ 8:50 am #

    Nice article! I noticed the Google Analytics Asynchronous Tracking yesterday, this is a great way of seeing where people after leaving your site & helps improve the bounce rate/conversions.

  3. Maren Kate

    January 27th 2010 @ 6:25 am #

    Found your site, beautifully designed! Cheers!

  4. MYO HAN HTUN

    January 28th 2010 @ 5:45 am #

    Thanks for your post. I really appreciate it.

  5. Marc

    January 29th 2010 @ 3:28 pm #

    @Carter

    I have notice quite a difference but only on the rare times google-analytics.com is being slow. I’d love to have a penny for every time I’ve seen ‘waiting for google-analytics.com’ in the browser status bar for more than a second. Using the asynchronous snippet should prevent this. There’s a nice little explanation of the old snippet by @rem over on jsbin.com.

  6. Sharry

    February 3rd 2010 @ 4:01 pm #

    @Marc
    You are missing the final line in the 1st part of the code:
    $(‘a:external’).addClass(‘external’);

  7. Marc

    February 5th 2010 @ 12:22 pm #

    @Sharry You could add a class of external to the links if you wanted to style them through CSS, but I was just concentrating on binding events to them in which case the :external filter is enough.

  8. Will

    April 1st 2010 @ 11:42 pm #

    Marc,

    I have to admit I’m not very technical so need some help implementing this. So based on the above, is this what the code should look like inside my blog template?

    1
    2
    3
    4
    5
    6
    7
    8
    9
    $(document).ready(function() {
         $.expr[':'].external = function(obj){
           return !obj.href.match(/^mailto:/)
             && (obj.hostname != document.location.hostname);
         };
         $('a:external').click(function(){
           _gaq.push(['_trackEvent','Outbound','Link',$(this).attr('href')]);
         });
    });

    Also, does each external link get tracked as a pageview as well or does it get separated out as just an event? Thanks so much.

  9. Marc

    April 2nd 2010 @ 12:27 pm #

    @Will

    Yes, that looks like it will do what you want. Assuming you have the google analytics asynchronous code somewhere so the _gaq object is defined when this code runs.

    They only get tracked as events not as pageviews, you could also track them as a page view by adding another _gaq call:

    1
    _gaq.push(['_trackPageView', '/external/' + $(this).attr('href').replace('http:\/\/', '')]);

    This will track page views under the /external/ URL on your site, so a tracked link to our blog would appear as /external/neutroncreations.com/blog in your analytics pages

  10. Jess Weiss

    July 28th 2010 @ 8:43 pm #

    Hi Marc – this seems to be exactly what I need. Can you please tell me where this gets loaded on the page? I have seen some other scripts that get put immediately above the call to Google Analytics before the . Does this get implemented there, or in the head? TIA!

  11. Mat Schaffer

    July 30th 2010 @ 5:15 pm #

    Does this definitely work? It looks like the call to _gaq.push fires the tracking request asynchronously which seems to imply that the browser might switch pages before the tracking request finishes.

    I’ll give it a try anyway. Thanks for the tip!

  12. Marc

    July 30th 2010 @ 6:30 pm #

    @Jess because of the way the google asynchronous javascript snippet works, you can actually put this anywhere you like, before or after the google async code. The _gaq variable acts as an array initially so each command is just being added as an item in this array, once the asynchronous code has loaded it executes each of the commands in the array and then turns the _gaq variable in to an object with a push function so subsequent .push() calls execute immediately

    @Mat It does work, the actual tracking request itself is not asynchronous, just the loading of the tracking code. So once this has loaded the events are tracked before the click handler returns. There is a small window where you could click a link before the page and tracking code has finished loading and it would not be tracked, but personally I think the benefit of the asynchronous tracking code far outweighs the very small amount of missed events. Here’s the events tracked on this very site over the past couple of weeks: http://cl.ly/1p0r

Leave a Reply


(Never published)


© 2010 Neutron Creations Ltd. Registered in England #6734162.

Say: hello@neutroncreations.com