thumbnail image for this experiment

google analytics tracker

description:

google analytics is a pretty powerful, and free, tool for website stats analysis. however, one of its main drawbacks is that it can only track pages that specifically call its tracking script. links to documents (Word, PDF, etc) and links to external websites are not tracked out-of-the-box.

this small script dynamically attaches the necessary explicit calls to google's tracker functions to any document or external links found in a page.

by specifying a prefix for external and document links it's possible to log any clicks in specific "fake" directories in the analytics reports.

for instance, with a prefix for external links set to /stats/external/, a link to http://www.foo.com/somedir/ will appear in google analytics as a click to /stats/external/http/www.foo.com/somedir/. by default, the prefix for document links is simply /, meaning that a link to /somedir/file.pdf on your site will be logged in its "native" location. if you prefer to see all documents logged separately, it is of course possible to change the prefix to something like /stats/documents/, so the above document would appear in the stats under /stats/documents/somedir/file.pdf.

in addition, this script fixes google analytics' site overlay view. if the overlay is detected (given away by the presence of a script element with id="_gasojs"), the href of document and external links is rewritten dynamically, ensuring that the correct percentage and click count are displayed in the overlay. the links are also "neutered" (their default behaviour is suppressed), so you don't accidentally click away from the overlay.

for debugging purposes, if you're running firebug in firefox, the script also writes to the console when a tracked link is clicked. this feature is commented out by default.

i originally wrote this back in april 2008, and it has since been used in production on a few high-traffic sites with excellent and reliable results. many thanks to stuart langridge for giving it a quick code review and suggesting some excellent optimisations.

tags:
analytics javascript google
completed:
20/09/2008

view this experiment