Menu

PDF Tracking in
Google Analytics.

PDF Tracking in Google Analytics

Jon Volks
Written By | @webproninja

For the past two weeks I’ve been going through the Google Analytics Academy in order to learn everything I can in order to get Google Analytics Certified. Although I’ve learned lots of awesome things, there is one tip that I really wanted to share. That would be how to track PDF files within Google Analytics.

When Google Analytics is installed in a site, it needs to be put within the HTML code on every page (assuming you are tracking every page). You can’t embed JavaScript code into a PDF file so the only way to capture that the user downloaded the pdf is to add an onclick event to the link.

<script>
jQuery(function($){
$("a[href$='pdf']").each(function(index) {
pdfLabel = $(this).attr('href');
pdfOnClick = "_gaq.push(['_trackEvent', 'PDF', 'Download', '" + pdfLabel + "']);";
$(this).attr("onClick", pdfOnClick);
});
});
</script>

What’s going on here? In simplest terms, when the page loads, this piece of code loops through all anchor tags that end with pdf in the file “href” attribute and adds an onclick event to it. When the user clicks on one of these anchor tags, the onclick event which will send information to Google Analytics about the PDF. The code above loops through ALL anchor tags on page, this way you do not have to add the onclick event to each one individually. This saves a lot of time for yourself and for any non-html web content users, they don’t have to worry about it.

The same script can be modified to use with other types of files as well; Word, Text, CSV, Excel, etc. I personally plan to go through my previous websites that have PDF files on them and add this script as well as make it part of my default template when I build new sites.

About The Author

Jonathan Volks is currently a Web Programmer at Skidmore College in Upstate New York. He enjoys everything about the Internet; from Search Engine Optimization to Web Programming. His hobbies include landscape photography and hiking the Adirondacks.

Leave a Reply

Your email address will not be published. Required fields are marked *