Google Analytics - tracking external links
Recently I was asked to implement extension which will track external links into Google Analytics. For me I was facing to problems. One I that if you have running 3rd party system it’s hard to implement anything, that will change all external links and the second one is that Javascript is not my cup of tea.
I found and implemented one solution which looks simple and works. Main idea is to listen to click on page and if the clicked element is anchor, call Googles page tracking before browser goes to that page. Another solution is to use jQuery, I’ll show this solution later.
First step is to create a listener, what will listen events on page and call another function to handle the action.
function addListener(element, type, functionName)
{
if(window.addEventListener) {
element.addEventListener(type, functionName, false);
}
else if(window.attachEvent) {
element.attachEvent('on' + type, functionName);
}
else return false;
return true;
}
addListener(document, 'click', trackingExternalClick);
Second step will be to create function, which will contain the logic for onclick action. Lets say that we want to track anchors which point to external page (starting with http:// or https://) and wants to know whats the clicked domain, we don’t need to know whole url. Name of the function will be trackingExternalClick (third parameter in addListener).
function trackingExternalClick(event) {
var cElem = (window.event) ? event.srcElement : event.target; //Get the clicked element
//If it is an Anchor
if(cElem.nodeName == 'A'){
// Check if link is external, not contain local domain
if(cElem.href.indexOf(location.host) == -1) {
//Replace characters not supported by Google Analytics
var url = cElem.href.match(/^([http|https]*):\/\/?([^\/]+)/g, "").toString().replace(new RegExp(/^([http|https]*)?:\/\//i),"");
var str = '/outgoinglink/' + url;
try{
pageTracker._trackPageview(str);
}
catch(err){ }
}
}
}
Same practice can be used to track download links (.zip, .pdf, etc.). We will only change lines 6 to 9.
if(cElem.href.indexOf(".pdf") == -1) {
//Replace characters not supported by Google Analytics
var url = cElem.href;
var str = '/download/' + url;
When you will have problems that these clicks are not tracked, try to move Google Analytics code to the head section of the page and these codes after GA. If you need anything more or wants to help with something, leave a message here.














