Tracking outbound links that open a new window with Google Analytics

So, here’s the problem:

…you want to use the tracking feature of Google Analytics to track all clicks on outbound links from your site, however, you also want those outbound links to open a new window…

If you simply follow the instructions to track outbound links you will discover that your links will no longer open in a new window (regardless of whether you are using Javascript or target=”_BLANK” to open the window.

And here’s the solution:

Apply the javascript to you hyperlink as usual…


<a href="http://www.example.com" onclick="recordOutboundLink(this, 'Outbound Links', 'example.com');return false;">your link text</a>

…but modify the tracking code as follows…


function recordOutboundLink(link, category, action) {
  try {
    var pageTracker=_gat._getTracker("XX-XXXXXXX-XX");
    pageTracker._trackEvent(category, action);
    setTimeout('document.location = "' + link.href + '"', 100;window.open(this.href))
  }catch(err){}
}

(Don’t forget to replace XX-XXXXXXX-XX with your tracking code)

…and that’s all — Outbound links with Google Analytics tracking and opening in a new window.