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.