Unobtrusive File Tracking with Google Analytics
Posted on 2008-02-02 (Updated on 2019-02-16)
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:
- Get all of the anchors present in the document using the getElementsByTagName() function
- Check through each anchor, and see if the target is a file with an extension that should be tracked
- If the anchor should be tracked, a 'click' event is added that calls the ga_file.Track() function
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.
- ga_file.js
- ga_file_doc.js - With full comments Feel free to use it, but leave the comment at the top with my credit/link please. Let me know how it works out; this is a very early version, and has not had any testing, so use at your own risk!
Tags: javascript