Skip to content
Fragmented Development

Unobtrusive File Tracking with Google Analytics

The Google Analytics folks recently announced the ability to track downloads of documents with their service. The method provided involved adding a onclick attribute to the anchor tag of whatever document you would like to track. Every time someone clicks the link to download/view the file, the _trackPageview() function is called and registers a hit for that file. Pretty simple, eh?

Well, unfortunately, it's not a very clean solution. We're supposed to add a new onclick attribute for each file we want tracked? We're supposed to just embed the Javascript right then and there? Isn't there supposed to be separation between presentation, behavior, and content? Ugh, I can feel my markup getting dirtier already.

To avoid garbling up my code, I've created a quick script that adds an event to any links that point to a file (as long as it's file extension is on the list). It requires an addEvent() function, like the Rock Solid addEvent() by Dustin Diaz, but that should be about it. The script itself is written in JSON, so it should be able to co-exist with any other scripts you have. Here's how it works:

The Extensions Array

All of the file extensions that should be tracked are kept in an array, ga_file.ext. If you'd like to track all Powerpoint slide shows that are downloaded from your site, simply add the string 'ppt' to the array.

Call the Initialization Function

The initialization function, ga_file.Init(), is called on the page load. It does the majority of the work in the script, including the following:

The Tracking Function

The tracking function, ga_file.Track(), is extremely simple. It makes sure the pageTracker object exists (this is the object Google Analytics uses for tracking), and if it does, it calls the _trackPageView() function to record the hit.

Of course, I don't expect you to take my word for it. Here's the link to the source files.

Tags: javascript


Add Your Comment