Tracking banners and other outgoing links – Automatically

Google Analytics hacksA word of caution – This is a tech tip and requires you to have a knowledge of html and javascript to implement and use it…

[This hack is for the legacy urchin.js tracking code.
Always refer to the Scripts & Downloads section for the latest version.
]

April 2011 – New async hack launched
This hack has been completely revise for the latest GA async code

 

Your site may offer a visitor a link to click through to an external web site such a subsidiary, an affiliate, advertiser or an trade organisation. For Google Analytics, a visit leaving your web site requires an edit to the page in order to track it. This is achieved by modifying your outbound links to call urchinTracker and is extremely easy to do. However, what if your web site has hundreds of separate outgoing links that are constantly evolving and being appended to? Clearly manually modifying each link becomes laborious and inefficient. To overcome this you can apply the example JavaScript code below to your web site:

[javascript]<script type="text/JavaScript">

// Only links written to the page (already in the DOM) will be tagged
// Script can be called multiple times

function addExtLinkerEvents() {
var as = document.getElementsByTagName("a");
var extTrack = ["mysite.com"];
// replace mysite.com with your web site domain

for(var i=0; i<as.length; i++) { var tmp = as[i].getAttribute("onclick"); // Track links off site – i.e. no GATC if (tmp != null && tmp.indexOf(‘urchinTracker’) > -1) continue;
for (var j=0; j<extTrack.length; j++) {
if (as[i].href.indexOf(extTrack[j]) == -1) {
var splitResult = as[i].href.split("//");
as[i].setAttribute("onclick",((tmp != null) ? tmp : "") + "urchinTracker(‘/ext/" + splitResult[1]+ "’);");

// the above must be on one line – from as[i]… to ");
break;
}
}
}
}
addExtLinkerEvents()
</script>[/javascript]

The script works by looking for links within the browser’s Document Object Model (DOM) that do not match the domain value given in the variable array extTrack. If the link does not match extTrack then it is considered an external link and so is modified to include the urchinTracker call. By this method, all external links will show in the Google Analytics reports as:

/ext/the-url-that-is-clicked-on

Where the-url-that-is-on clicked on is minus ‘http://’. You can modify the JavaScript to adjust the path as required,

IMPORTANT: The position of this code within your page is important. The code must be placed after your call to the Google Analytics Tracking Code (GATC). Alternatively, you can place the addExtLinkerEvents() call in an onLoad event handler and host the provided JavaScript in a separate file. As an example I show this below, assuming the javascript is hosted in a file called trackExternal.js, as follows:

[javascript]
<script src="http://www.google-analytics.com/urchin.js" type="text/JavaScript"></script>
<script src="/trackExternal.js" type="text/JavaScript"></script>
<script type="text/JavaScript">

_uacct = "UA-XXXXX-Y"; urchinTracker();

</script>
…your remaining web page content…
[/javascript]

A note on performance: Each time your page loads, this script will go through all links referenced on the page to see if it is external. Clearly the more links on your page, the harder the script must work. As long as the number of links on each page number in the hundreds and not thousands, performance should not be a problem.

Also note that for pages with a large number of links, it is possible that visitors will click on an external link before the script has modified it. The result is that click through will not be tracked by Google Analytics which is an accuracy consideration that effects all web analytics vendors.

Did you find this tip useful? I am considering writing more of these tech tips if you feel they are useful. Please provide your feedback with a comment.

Looking for a keynote speaker, or wish to hire Brian…?

If you are an organisation wishing to hire me and my team, please view the Contact page. I am based in Sweden and advise organisations in Europe as well as North America.

You May Also Like…

Sayonara Universal Analytics

Sayonara Universal Analytics

My first Google Analytics data point was 15th May 2005 for UA-20024. If you are of a certain age, that may sound off...

26 Comments

  1. Tony Pinto

    I’ve read through all of the comments twice, but cannot tell for sure whether the IE issue has been resolved. Does this script work reliably for all browsers? If so, it’s a godsend. Well done.

    Reply
  2. Ralph Jones

    Although I am still a novice at Java script but I am working on that area to get better, the script you have given looks really good, will try it out and let you know.

    Reply
  3. Timo

    Hi Brian,
    I’ve just downloaded the code for the new GATC but it seems to have a reference to the old code
    if (tmp.indexOf(‘urchinTracker’)
    Shouldn’t it refer to pageTracker instead?

    Thanks,
    Timo

    Reply
  4. Suzan

    Thank you so much. I will definitely take your advice and recommendation into consideration.

    Reply
  5. Victor Geerdink

    Hi Suzan,

    You should at least see something, on average about 30-50% of the Internet uses IE6 and Firefox. If you should implement the script depends on what your alternatives are.

    If your website isn’t that big (and doesn’t have a lot of outgoing links) it should be possible to tag your links, documents and mail addresses manually and you will be sure about the accuracy of your data. If your website is a lot bigger and you can’t do it manually than you should first try to seek a server side solution to implement the code (your web developer should be able to write a script that can detect links, etc. and add a extra piece of code,in either XSL-T, php, asp, pearl or whatever code your system is using), you can give the web developer Brian’s code as an example how it could be done, than they just have to translate it into their own code. The main advantage about this solution is that you will not have to worry about browser compatibility if it works than it works.

    If your website is to big and you don’t have the budget/time to code in on a server side, than you should implement Brians piece of code. 50% should at least give you statistical relevant information and you will be able to get a good idea what is happening on your website, but you might miss some interesting insights because browser usage can sometimes say something about your users. You will just have to keep in mind while analysing (and be careful while making assumptions/correlations) that the numbers are not accurate and biased.

    Reply
  6. Suzan

    So no point in me putting the script in if most of our users are IE users? That would explain why I haven’t seen anything tracked thus far? Unless I’m doing it wrong

    Reply
  7. Brian Clifton

    Katie: I am pretty sure this hack can be made to work with redirects though it is beyond my capabilities. I would try getting it to work manually by editing the link itself (with an onClick event handler) on a test page.

    Holger: Many thanks for pointing this out. I have had a closer look at my reports and indeed for these virtual pageviews, there are none for Internet Explorer!

    Firefox, Opera, Safari and Chrome all work, so I guess we will have to wait for IE8 until it is fixed – fingers crossed…

    Reply
  8. Holger Tempel

    Hi Brian,

    we did some extensive testing on your scripts as well as some enhancements for customer’s purposes.

    After all we ran into the incompatibility issue with Microsoft’s IE (almost all versions) regarding the setAtribute (additional information here: http://www.quirksmode.org/dom/w3c_core.html#t910 and
    http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html).

    What’s your approach to this problem?

    Cheers,
    Holger

    Reply
  9. Katie Wang

    What if your link is ON the domain but it’s actually a redirect to an affiliate page. Because the redirect is php, I can’t put google’s code on there and still have the redirect work. Is there a way of tracking these links?

    Reply
  10. Brian Clifton

    Hi Robert – unfortunately you cannot use the browser DOM (Document Object Model) to track Flash events. Flash is a walled garden in that respect. In order to track these, the javascript has to be added within the fla file.

    The good news however, is that I have modified my script to also track mailto: links – see the latest version on http://www.advanced-web-metrics.com/blog/ga-scripts/

    enjoy 🙂

    Reply
  11. Robert Austin

    Any ideas on if it is possible to track flash events through this script? I mean in theory is it possible?

    We often have book online buttons done in flash which I would like to track to.

    Reply
  12. Robert Austin

    This script is setup on http://www.novotelningaloo.com.au

    by the way my last post was somehow muddled up. Your instructions on how to install the script are fine Brian.
    Anders script needs some sort of documentation.

    I did some more testing, I changed the /downloads path in the default script to be /downloads/

    This has made it start counting the pageviews with the /ext/
    which is even stranger!

    Reply
  13. Brian Clifton

    Robert: something odd there – can you post the url of a sample page on your site that has the script.

    Reply
  14. Robert Austin

    Hi Brian,

    Great script. My testing is showing that downloads are appearing in google analytics with malformed tagging.

    for some reason all my downloads appear as /downloads.au/
    in the content report. The site is .com.au? perhaps my implementation was wrong, maybe you could include some brief instructions in the header of you .js file Anders.

    Any plans to add tagging of mailto: links to this script?

    I also tested iih’s script ( mainly because it said it would track mailto: links ) Unfortunately I was unable to get this to work. Perhaps

    Reply
  15. Anders Møller

    Hey,

    I have made an new version of your script to some of my clients, one of biggest requirement for the script was that i could be install on any web site by a no tec person, and not conflict with existing JS code. I also add some extra features to track download of documents, mailto and onclick events.

    script: http://trend.iih.dk/js/analyticsTools.js

    Example’s usage:

    Example 1, set the domain to my page and add tracking on only normal and mailto links

    analyticsTools.domains = [‘mysite.com’,’www.mysite.com’];
    analyticsTools.trackEvents = [‘link’,’mailto’];
    analyticsTools.addLinkerEvents();

    Example 2, set the domain to my page and add tracking on download of doc’s
    analyticsTools.domains = [‘mysite.com’,’www.mysite.com’];
    analyticsTools.trackEvents = [‘download’];
    analyticsTools.downloadDocs = [‘.doc’,’.xls’,’.pdf’];
    analyticsTools.addLinkerEvents();

    Comments, bugfix’s and improvements are more then welcome

    Reply
  16. Brendan Halloran

    I really like this js code Brian. Is it possible to provide one snippet of code that will not only automatically track outbound links but also file downloads (pdf, doc, etc)?

    Reply
  17. BJ Wright

    Yes, these tips are valuable. Please continue to write more like this!

    Thanks,

    BJ

    Reply
  18. Brian Clifton

    Andre: You are correct in that the purpose of using urchinTracker in this way is to create additional pageviews (virtual pages), but this is entirely valid. For example, if you add content to your web pages that encourages people to click away, then you should measure it. Although not ideal, treating this as a pageview gives you great insight into the value of those links – that is, they could be one of your goals with an associated goal value. Many sites make a living out of doing just that – acquiring visitors and them encouraging then to click away. See my Recommended Reading section for the affiliate links to Amazon for example! In fact this ‘virtual pageview’ technique is the same technique used by all page tag vendors for tracking a pdf download for example. Joost’s idea of keeping them in a separate profile is also a great idea.

    Tim: Speaking of performance, one advantage of using such a widely adopted tool as GA, is that it is the same js file used for all implementations. So, if you visit say Blockbuster video one day, then Nestle a week later, the urchin.js file (essentially the page tag/beacon that collects data) will be cached by your browser. Relieving the visitor of the need to download again.

    Joost: nothing in my mailbox…

    Reply
  19. Tim Leighton-Boyce

    Feedback: yes, please. More of these. This kind of thing is extremely welcome.
    I must admit, I am concerned about performance. Our pages are already loaded with code to help US which does nothing for the user experience, apart from slow them down! Biggest issues there tend to be with calling stuff from other servers, though, not this kind of thing.

    Reply
  20. Joost de Valk

    @Andre: I guess you could remove the pageviews you create by scripts like these on an extra profile? That way you could have the data and still have reliable pageviews as well.

    @Brian: I’ve been working on a WordPress plugin to do this and a bit more, email about that is in your inbox 😉

    Reply
  21. Ben

    Brian,

    I like your solution to link tracking. It is much easier than even using server side code to include link tracking.

    I would love to see this code integrated into Google Analytics. It would be great to have an Outbound link tracking report in the interface.

    Reply

Leave a Reply to Brian Clifton Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share This