Vitavonni

Fri, 04 Dec 2009

Tracking outgoing links with Google Analytics

Here's a code fragment to track outgoing links with Google Analytics. As usual, use it at your own risk. I can not give you support for Google products, for obvious reasons.

To use it, you need at least understand where to put it (call it in a try-catch in onLoad) and how to adjust the variable name of your page tracker (I'm not using the default).

function trackLinks(){
  var as=document.getElementsByTagName("a");
  var ig=["mydomain.tld","google-analytics.com"];
  for(var i=0; i<as.length; i++) {
    var ignore=false;
    var oc=as[i].getAttribute("onclick");
    if(oc!=null){
      oc=String(oc);
      if(oc.indexOf('urchinTracker')>=0
      || oc.indexOf('_trackPageview')>=0
      || oc.indexOf('javascript:')>=0)
        continue;
    }
    if(as[i].href.indexOf("mailto:")<0){
      for(var j=0;j<ig.length;j++){
        if (as[i].href.indexOf(ig[j])>=0)
          ignore=true;
      }
    }
    if(!ignore){
      as[i].onclick = function(){
        var o=this.href.replace(/:\/*/,"/");
        pt._trackPageview('/out/'+o)+";"
        + ((oc!=null)?oc+";":"");
      };
    }
  }
}

This code tries to attach an onload handler to any outgoing link, ignoring internal links or links that use JavaScript. If such a link is clicked, it generates a virtual page access with an "/out/" URL that can be analyzed in Google Analytics.

A side benefit (apart from knowing which links are interesting to your visitors) is that you should get more accurate "time on page" statistics for your pages.

[category: /en/web | Permalink]
Menu
[planet.debian]
[planet.xmlhack]
[planet SELinux]
[munichblogs]
[email]
[RSS 2 feed]
[English RSS 2]
Categories
< December 2009 >
SuMoTuWeThFrSa
   1 2 3 4 5
6 7 8 9101112
13141516171819
20212223242526
2728293031  
Archives
2010-Mar
2010-Feb
2010-Jan
2009-Dec
2009-Nov
2009-Oct
2009-Sep
2009-Aug
2009-Jul
2009-Jun
2009-May
2009-Apr
2009-Mar
2009-Feb
2009-Jan
2008-Dec
2008-Nov
2008-Oct
2008-Sep
2008-Aug
2008-Jul
2008-May
2008-Apr
2008-Mar
2008-Feb
2008-Jan
2007-Dec
2007-Nov
2007-Oct
2007-Sep
2007-Aug
2007-Jul
2007-Jun
2007-May
2007-Apr
2007-Mar
2007-Feb
2007-Jan
2006-Dec
2006-Nov
2006-Oct
2006-Sep
2006-Aug
2006-Jul
2006-Jun
2006-May
2006-Apr
2006-Mar
2006-Feb
2006-Jan
2005-Dec
2005-Nov
2005-Oct
2005-Sep
2005-Aug
2005-Jul
2005-Jun
2005-May
2005-Apr
2005-Mar
2005-Feb
2005-Jan
2004-Dec
2004-Nov
2004-Oct
2004-Sep
2004-Aug
2004-Jul
Other links:
Swing and the City - Lindy Hop in Munich