Tracking all outgoing links with Google Analytics
Published on 15. April 2007 inI wanted to try and find a way to track all of the outgoing links on my blog, without haven to modify the html of the link. What I found was that using javascript listeners would probably be the best solution. Actually this technique can be used for a lot of stuff, but this is what I did:
<script type="text/javascript">
// Cross-browser implementation of element.addEventListener()
function addListener(element, type, expression, bubbling) {
bubbling = bubbling || false;
if (window.addEventListener) { // Standard
element.addEventListener(type, expression, bubbling);
return true;
} else if (window.attachEvent) { // IE
element.attachEvent('on' + type, expression);
return true;
} else return false;
}
//This is what i want to do whenever someone clicks on the page
function itHappened(evt) {
//Get the clicket element
var tg = (window.event) ? evt.srcElement : evt.target;
//If it is an A element
if (tg.nodeName == 'A') {
//And it is not an internal link
if (tg.href.indexOf(location.host) == -1) {
//Replace all odd characters, so that it works with Analytics Niavgation analysis
var url = tg.href.replace(/[^a-z|A-Z]/g, "_");
var txt = tg.innerHTML.replace(/[^a-z|A-Z]/g, "_");
var str = '/outgoinglink/-' + txt + '-' + url;
try {
//Track it
urchinTracker(str);
}
catch (err) {
//alert('error: ' + err);
}
}
}
}
//Add the click listener to the document
addListener(document, 'click', itHappened);</script>
I hope you can use it. Any comments or advice is very welcome :-)
Related posts
Comments
Comments disabled
Comments are disabled for this post.

On 20. June 2007 by Google Analytics: How to track all your outgoing links the easy way »Technology News | Venture Capital, Startups, Silicon Valley, Web 2.0 Tech
[...] You can find the script here. [...]
On 21. June 2007 by Douglas Karr
Morten,
Have you had any luck with custom filters in Google Analytics? I've been trying to track my categories in Google Analytics (http://www.douglaskarr.com/2007/06/09/analytics-categories/) but can't seem to get the filter to work properly to report it.
Doug
On 21. June 2007 by Morten Bock
Hi Douglas. I have only used filters briefly when triyng to exclude my own ip adress from the stats, but it didn't seem to work, så I did that on my websites serverside instead.
I did however use the goal tracking system with regular expressions, and i've use this tool with great joy to test if my regex matched the right url's.
On 09. August 2007 by hayesy
So all I have to do is copy that into my site code (Header or some such place)?
Do I need to set anything up inside google analytics?
On 10. August 2007 by Morten Bock
Yeah, that's pretty much it. In your google analytics alle the outgoing links will be shown as a visit to a page like: /outgoinglink/some_link_text/http_.... and so on. So you could filter all link clicks like you would with normal pages.
On 29. August 2007 by Brendan Halloran
Hi Morton,
Do you also have some Google Analytics javascript for tracking downloads - pdf's, doc's, etc?
On 30. August 2007 by Morten Bock
You can track them using the same code. You just need to adjust the code in line 24 to determine what kind of document the href attribute is pointing to.
On 31. August 2007 by Brendan Halloran
Thanks for the advice about tracking downloads Morton. Unfortunately, I am absolutely useless when it comes to javascript - would you be able to provide the download code in a separate post?
On 18. December 2007 by Planet Apex
Hi,
I have a free blog at Blogger's blogspot. Can this be used there? if so can you pls tell how?
Thanks
On 20. December 2007 by Morten Bock
Well, I am not that familiar with blogger, but if you have permission to add anything to the head section of your template, then it could be used.
On 24. December 2007 by Planet Apex
Hi Morten,
I put it in a html/javascript widgest in my blogspot sidebar. It is working. Thanks so much for this cool hack. :)
On 24. December 2007 by Morten Bock
Good to hear. Thanks for reporting back with your solution :-)
On 05. January 2008 by susan
love it. but, I see the date of this post precedes the new GA code. will this code work with this GA code?
var gaJsHost = (("https:" == document.location.protocol) ?
"https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost +
"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
var pageTracker = _gat._getTracker("UA-3331287-1");
pageTracker._initData();
pageTracker._trackPageview();
Also is it possible this code would be able to detect Flash on click events that use buttons to load and unload other SWF files rather than getURLs that click through to a page/
On 05. January 2008 by Morten Bock
Susan,
I _don't_ think this will work out of the box with the new ga code, since the old functions are not available.
However, it would probably not be too difficult to adjust the code, since the only ga specific code is line 32 in the above example. So if you can find the appropriate method for registering at click, you can just insert that in stead of the urchinTracker().
It seems that the new code is much more flexible regarding event tracking. Take a look at their guide that also has examples on how to track from inside flash movies:
Event Tracking Guide - BETA
On 05. January 2008 by susan
Morten
Thanks!
The syntax for tracking an onRelease event in Flash is
on(release) {
getURL("javascript: pageTracker._ trackPageview
The outgoing HTML version is
<a href="http://www.example.com" rel="nofollow">
So does that mean line 32 should be:
//Track it
pageTracker(str);
On 05. January 2008 by Morten Bock
Susan,
As I wrote earlier, I have not yet familiarized myself with the new ga code, so you would have to consult their documentation for guidance on the new api methods.
On 06. January 2008 by susan
I implemented your code with the pageTracker(str); modification, I'll let you know in a couple days whether it works.
In the meantime from my del.icio.us tags:
gaTracker - Google Analytics Integration for jQuery
November 12, 2007
http://plugins.jquery.com/project/gaTracker
On 06. January 2008 by Morten Bock
Looks like a nice piece of code in the jQuery plugin.
Thanks for the link.
On 05. February 2008 by Colin
Susan, any update as to how your modification works with the new GA code? Or has anyone else figured this out?
On 08. February 2008 by Andrew Ziem
Thanks. I have the code working OK by changing
urchinTracker
to
pageTracker._trackPageview
according to
http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55527
However, is there a way to prevent these stats from affecting my pageviews? My pageviews are inflated with all the outbound clicks, so it's hard to get apples to apples comparison.
Also, the way this code strips URLs could be improved. It removes numbers but does not need to. Would escape() be better than a regex?
Andrew
On 08. February 2008 by Andrew Ziem
It would be nice to see Morten Bock's code integrated with the following:
http://www.seobook.com/archives/001370.shtml
It tracks AdSense clicks (but Morten Bock's code does not seem to). Also, it seems to have more robust support for various browsers.
Andrew
On 08. February 2008 by Morten Bock
Andrew: "However, is there a way to prevent these stats from affecting my pageviews?"
You could use the Google Analytics profiles and filters to filter out the outbound pageviews for your regulars stats, and then create a profil that only shows outbound links.
Andrew: "Also, the way this code strips URLs could be improved. It removes numbers but does not need to. Would escape() be better than a regex?"
When I made this code almost a year ago, the escape() function was not enough, because the Analytics UI cut off parts of the url on a lot of characters. Since then the UI has changed, so I don't know if it will work now. Try it out :-)
On 08. February 2008 by Andrew Ziem
Morten,
Hmm. For each tracking code, the data is logged into one profile. I'm not sure how this would work with profiles: wouldn't I need two copies of the GA tracking code? Would they interfere with each other? And aren't GA filters applied at the time of logging (instead of at the time of reporting)?
Maybe I don't yet understand GA well.
Andrew
On 23. February 2008 by Laymybet
Great find this and the js will be really useful for us when it comes to tracking outgoing links on our website. It worked first time and was easy to implement. Thanks Morten.
On 13. March 2008 by Mike
Hi Marten. Cheers for this. I've just put your code onto my blog and am looking forward to getting the results. Thsi has been a great help - as my JavaScript and WordPress skills are absolutely minimal.
On 22. April 2008 by ziriyan
if these code didn't work, the cause of "Track it" secation, you can replace that as below:
//Track it
pageTracker._trackPageview(str);
because you used the new GA code which trigger must be use the new one
On 23. June 2008 by Michael
Cheers for this. I've just sent this on to our development company to implement for us. Looks a whole simpler than the massive changes we thought we were going to have to organise.
On 18. July 2008 by Doug Moore
Hi, your script just might work for me. Just wondering though, my outgoing html links are called as a variable from a column of a database using VBScript:
<a href="" target="_blank">
Do you think your listener script would work in this way? Thanks for any insight you have.
Best,
Doug
On 18. August 2008 by Timo Luege
Hi Morten,
I'm working for the Red Cross and we basically hve to different kinds of outgoing links. "Real" outgoing links go to another domain but also a lot of links that go directly to PDF documents that are hosted on our servers but which cannot be tracked with GA. Unfortunately I'm not fluent in Javascript - but am I right to assume that your script would not be able to show us people who "exit" to PDFs?
Thanks,
Timo
On 20. August 2008 by Morten Bock
Hi Timo
You would need to change lines 24-29 to find links that point to .pdf files instead of external domains. There are a thousand different ways to do this, so I would suggest that you find someone with a bit of javascript skills to choose the right solution for you.
On 19. November 2008 by Tony
Does this tracking script work with the new GA tracker code?
On 19. November 2008 by Morten Bock
Tony> As far as I know, it works, but the method is deprecated, since there are new and better ways to do this in the new GA tracker API.
On 30. December 2008 by yzaragoza
How can I modify this code to records when users click on an Image...
right now it only works when they click on links that are text
(if(tg.nodeName == 'A'))
On 30. December 2008 by Morten Bock
yzaragoza>
You would have to create some logic that checks if the clicked element has an ancestor element that is an A element. Try asking for help on a javascript forum if you are not familiar with javascript and traversing nodes.
On 31. December 2008 by A bit of stats for the year 2008 at Morten Bock
[...] http://www.mortenbock.dk/google-analytics-outgoing-links-50.htm [...]
On 27. July 2009 by Justin
Andrew - Were you able to this solution of yours to work?
--------------------------
Thanks. I have the code working OK by changing
urchinTracker
to
pageTracker._trackPageview
according to
http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55527
However, is there a way to prevent these stats from affecting my pageviews? My pageviews are inflated with all the outbound clicks, so it’s hard to get apples to apples comparison.
Also, the way this code strips URLs could be improved. It removes numbers but does not need to. Would escape() be better than a regex?
Andrew