Alternate way to have Google Analytics track PDFs

1 minute, 26 seconds

Recently I needed a way of tracking PDF viewing on a web site. Google Analytics (GA) does a great job of tracking page views, but they require JavaScript to work. Further, a PDF download will not fire any JavaScript and is only tracked in the web server log, of which GA knows nothing about. What to do?

For starters, you could use GA’s tip: How do I track PDFs on my site? The big caveat with this technique is that the GA JavaScript takes a sec to load, and is generally best kept at the bottom of the page so the user experiences all your content loading “quickly” while the GA JavaScript can load “slowly” with no perceived slowness. Since most modern browsers are not really multi-threaded, moving the GA code to the top will give the user a slow, bad experience.

A better technique is to use JavaScript just like GA recommends, but instead of firing their page view code, fire your own in an iframe! I have a site wide JS file I use which I added this function to (JQuery required):

// way to fire a page request in hidden iframe good for
// doing Google analytic tracking for offsite links, PDFs etc.
function loadFrame(goto_url)
{
   if ($("#loaderFrame").attr("id") != undefined){
      $("#loaderFrame").attr("src",goto_url);		
   }
   return true;
}

Now on any page that I want to track PDFs, I have a link that looks like this:


   PlipBlogger


The net result is that:

  1. link is clicked
  2. loadFrame() gets called
  3. loadFrame() sets the source of your iframe to be pdfTracker, thus loading the iframe with you PDF as it’s query string
  4. the ender user sees none of this and their browser natively handles the PDF download.

On the /pdfTracker page, you would send the user’s browser a small payload include the GA JavaScript to track that this PDF was loaded. When you next got to GA you should see all your PDFs behind the /pdfTracker? URL. Handy!

Leave a Reply

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