Tracking document downloads in Google Analytics

We've been using Google Analytics for some time, both for a number of clients, and for our own site. It's a very real and impressive way to measure what areas of a site people are most interested in. What's even better is that it's free, you can signup anytime.

Tracking standard webpages is a breeze with a couple of lines of javascript placed at the bottom of your page, for most sites there is generally a single file to modify and/or an automated way to do this.

Tracking documents such as PDFs and word is not so easy however, looking at the GA help files, it suggests that you manually tag every PDF or word document with some javascript like this

<a href="/files/map.pdf" onClick="javascript:urchinTracker ('/downloads/map'); ">

This is fine for a small site, but once you get into a site of any size then it becomes a tedious manual process, some content management systems can help, but from our experience these systems are limited in what they can do.

After some thinking and googling around for a solution that avoids the mass find and replace, we came across this clever idea - to attach some event listeners to all document links.

So I've taken the code and modified it a little to make it just for file downloads, and to cover more file extensions that the original. This will track the following file types:

  • PDF (.pdf)
  • Microsoft Word (.doc)
  • Microsoft Excel (.xls)
  • Microsoft PowerPoint (.ppt)
  • Microsoft Visio (.vsd)
  • Microsoft Visio XML (.vxd)
  • ZIP Archive(.zip)
  • RAR Archive (.rar)
  • Text file (.txt)
  • Downloadable Javascript file (.js)
  • Downloadable CSS file (.css)
  • Executable (.exe)
  • NEW Windows Media Audio (.wma)
  • NEW Quicktime (.mov)
  • NEW Audio Video Interleave (.avi)
  • NEW Windows Media Video (.wmv)
  • NEW Mpeg Layer-3 (.mp3)

The result - some unobtrusive javascript, to use simply download the js file, place it somewhere on your webserver and paste the following code directly above your standard Google Analytics tracking code (which by the way, should be as near the end of the <body> tag as possible).

<script src="/js/taglinks.js" type="text/javascript"></script>

(Don't forget to replace the '/js/taglinks.js' with the correct path to the javascript file)

Hey presto you've now got tracking for all downloadable files!

UPDATE: I've update the Javascript so it won't throw a wobbly if there are anchor links on the page, also some new file types have been added (see above).

UPDATE: The script now tracks external links as well as document downloads.

Categories: Web analytics and Web Site Management