Custom Outbound Link Tracking With Google Analytics

Oct
10

I have been using Google Analytics for years, but have never attempted to extend its functionality to track outbound clicks. Lately I decided to add that functionality, and here is how I did it.

The default JavaScript code declares a variable named _gaq. If yours is named differently, adjust the following code accordingly.

First, you need to define the following trackOutboundLink function:

<script type="text/javascript">
function trackOutboundLink(link, category) {
   try {
      _gaq.push(['_trackEvent', category, link.href]);
      // redirect once click event is sent to Google
      _gaq.push(function() { document.location.href = link.href });
   } catch(e){}
   return false;
}
</script>

Then in the links that you would like to track, set the onClick attribute as follows:

<a href="example.com" onClick="return trackOutboundLink(this, 'Outbound Links')">Link</a>

You will then begin to see data accumulating in Google Analytics under Content->Events->Outbound Links.

Of course, you can change the "Outbound Links" in the onClick attribute to whatever you wish, and it will be put under the corresponding event in Google Analytics.