Category Archives: jQuery

Tracking file downloads with Google analytics

Google analytics (let’s call it GA) is a commonly used tool for keeping track of visitors to your website. In this article, I will highlight how to use this tool for tracking file downloads. This works for the so-called “Universal analytics” or newer version of the script, typically of the form: UA-XXXXXXXX-X.

The baseline use of GA involves signing up for a free account and then placing a small JavaScript snippet in all pages you wish to track. This enables us to track how many times that page was viewed and from which corner of the Earth your visitors are coming from. But if you have a link to a PDF file in that page, there is no way of knowing whether a user actually downloaded that PDF file or not.

Let’s assume that you have a button set up such that when the user clicks on the button, you send him the PDF file he requests.

An easy way to actually make this work is to use jQuery. We make an object based on the id of the HTML tag (button in this case) and then fire off an event to GA before sending the requested PDF file to the user. Something like this:

  • You can pick any string you wish to replace ‘PDF File’, ‘Download’ and ‘name of your file’. In general, these provide more and more granularity for the description of whatever it is the user is downloading.
  • The setTimeout() used above is a hack to buy some time for the event to fire off a message to GA. In the above example, I have used a delay of 1000ms between the user clicking the button and the client actually requesting the PDF file from the server.
  • The ‘_self’ parameter is to open the window in the same page and tab.

You can test in real-time if your events are firing by opening GA and navigating to Real-TimeEvents. They will also be available for analysis in BehaviorEvents.