July 23, 2024

Hello my dear Sitecore Family,

Firstly, Thank you so much for your response on my last post — how to Configure Google Analytics for a Sitecore Website via Twitter and Email. It inspired my to write more on the connecting yet quite useful topic. In case you missed the last post, check it out here: http://varunvns.wordpress.com/2014/09/22/configuring-google-analytics-for-a-sitecore-website/

Today, lets look at how to track PDF downloads in Google Analytics.

  • Basic understanding of Tracking PDF Downloads in Google Analytics:

There are two ways in which we can track them:

  1. As a Virtual PageView
  2. As an Event.

But logically, I feel that tracking a PDF download as an Event is better – still choice is yours, and we will also discuss how to track it as a virtual PageView if required.

How can we configure this?

What we need to do is, we need to put the Google Tracking code in the link of PDF, so that whenever it is clicked, it sends the required information to Google. This information is inturn available to us via Google Analytics.

A sample given by Google for the same is as follows:

[code language=”javascript”]

<a href="#" onClick="_gaq.push([‘_trackEvent’, ‘Videos’, ‘Play’, ‘Baby\’s First Birthday’]);">Play</a>

[/code]

  • Basics of Configuring and Tracking PDF Downloads in Google Analytics:

We will first discuss how to track PDF Downloads as events in Google Analytics. By the end of the post, we will also discuss a few changes, so that we can configure PDF downloads as a Virtual Pageview. As with the case of Configuring Google Analytics, we can do this in one of the two ways – either using Classic Google Analytics (ga.js) or using Universal Google Analytics (analytics.js)

Still, we need to make sure that Google has already mentioned, to upgrade to Universal Analytics from Classic Analytics. So its good to use that.

Add-Universal-Analytics

 

Pre-requisites:

  1. Google Analytics must be configured in our website.
  2. Media.RequestExtension in our web.config is not set to ashx (because, in that case, your PDF will have an extension of .ashx in the HTML and if so, then how can we append the Google tracking code to it. (http://sitecoreblog.patelyogesh.in/2013/09/sitecore-media-url-remove-ashx-extension.html)

Events Classic Google Analytics (ga.js)

There is a nice post written by Mr. Mortaza Kamal Nourestani, to track PDF Downloads in Sitecore for Classic Google Analytics – http://nourestani.wordpress.com/2012/06/12/how-to-track-downloads-in-google-analytics/

So its a great thanks to him for this.

Events Universal Analytics (analytics.js)

A small piece of code written by me, inspired by Mr. Mortaza.

[code language=”javascript”]

<script type="text/javascript">
if (typeof jQuery != ‘undefined’) {
jQuery(document).ready(function ($) {
var filetypes = /\.(pdf)$/i;
var baseHref = ”;
if (jQuery(‘base’).attr(‘href’) != undefined) baseHref = jQuery(‘base’).attr(‘href’);
jQuery(‘a’).each(function () {

var href = jQuery(this).attr(‘href’);
if (href) {

if (href.indexOf(‘?’) != ‘-1’) {
href = href.substring(0, href.indexOf(‘?’));
}
if (href.match(filetypes)) {
jQuery(this).click(function () {
//var ga = ga || [];
var extension = String((/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined);
var filePath = String(href);
var filename = filePath.replace(/^.*[\\\/]/, ”)
ga(‘send’, ‘event’, ‘PDF-Downloads’, filename, document.URL);
if (jQuery(this).attr(‘target’) != undefined && jQuery(this).attr(‘target’).toLowerCase() != ‘_blank’) {
setTimeout(function () {
location.href = baseHref + href;
}, 200);
return false;
}
});
}
}
});
});
}
</script>

[/code]

Both the above code snippets, do the same thing, — find the extension “PDF” and append the Google Analytics Event Tracker code into it. Thus, whenever the PDF link is clicked — the PDF is opened or downloaded — information is gathered by Google and shown to us.

 

Basic Steps:

  1. Make sure that Google Analytics is Configured for the current Sitecore Site. In case it isn’t follow this article to configure it – http://varunvns.wordpress.com/2014/09/22/configuring-google-analytics-for-a-sitecore-website/
  2. Create a Sublayout in our Sitecore Solution.
  3. Copy one of the above given code (preferably Universal Analytics) to the Sublayout.
  4. Statically bind the Sublayout to all (one or more main layouts of the Sitecore Site. (http://varunvns.wordpress.com/2014/07/03/sitecore-beginner-static-and-dynamic-binding/)
  5. Upload a test PDF and link it to one of your Sitecore content item. (I haven’t checked, what would happen if we have upload as ashx you can check and definitely let me know. But better check the pre-requisite above.)
  6. Open any page with a PDF link.
  7. When the page load completes, view the Page Source.
  8. Search for the PDF link (anchor tag using which the PDF is linked)

These are the simple basic steps, which would make it work just fine. They will be displayed in a Category called PDF-Downloads, as that’s what we have mentioned in the code above.

Now, lets consider a case, wherein we have different PDFs for different use and want to configure them category wise in Google Analytics. But before that, lets first understand something.

PDF-Downloads-GA-Understanding

So now, if we want to categorize the PDFs further based on need or Client requirement and as we said in the beginning of the post, if we want to configure it as a virtual PageView instead of Event Tracking on the fly, we can do that too. Lets see how.

Advanced Steps:

  1. Make a section in Global Sublayouts (which is shared between all the sites in our solution) and lets create a Sublayout GA-PDFDownloads.
  2. Copy the  Universal Analytics code given above with just one line of change — adding Properties instead of Hit Type and Category as in the screenshot below:PDF-Downloads-Sublayout-code
  3. Statically bind the Sublayout to all (one or more main layouts of the Sitecore Site. (http://varunvns.wordpress.com/2014/07/03/sitecore-beginner-static-and-dynamic-binding/)
  4. In the Template of HomePage of the website or in a Global Settings Section template of a site, create two fields to store Data about Google Analytics PDF Downloads.PDF-Downloads-Template-Sections
  5. Add the field values in the items. PDF-Downloads-Item-Values6.  In the code behind of the Sublayout, initialize the Properties and in the Page_Load function write a code to fetch their values as below:PDF-Downloads-Sublayout-code-behind

 

Want the code? Well, here it is!

[code language=”javascript”]
<script type="text/javascript">
if (typeof jQuery != ‘undefined’) {
jQuery(document).ready(function ($) {
var filetypes = /\.(pdf)$/i;
var baseHref = ”;
if (jQuery(‘base’).attr(‘href’) != undefined) baseHref = jQuery(‘base’).attr(‘href’);
jQuery(‘a’).each(function () {

var href = jQuery(this).attr(‘href’);
if (href) {

if (href.indexOf(‘?’) != ‘-1’) {
href = href.substring(0, href.indexOf(‘?’));
}
if (href.match(filetypes)) {
jQuery(this).click(function () {
//var ga = ga || [];
var extension = String((/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined);
var filePath = String(href);
var filename = filePath.replace(/^.*[\\\/]/, ”)
//ga(‘send’, ‘event’, ‘PDF-Downloads’, filename, document.URL);

ga(‘send’, ‘<%= GoogleAnalyticsHitType %>’, ‘<%= GoogleAnalyticsCategory %>’, filename, document.URL);

if (jQuery(this).attr(‘target’) != undefined && jQuery(this).attr(‘target’).toLowerCase() != ‘_blank’) {
setTimeout(function () {
location.href = baseHref + href;
}, 200);
return false;
}
});
}
}
});
});
}
</script>
[/code]

[code language=”csharp”]
public string GoogleAnalyticsHitType { get; set; }
public string GoogleAnalyticsCategory { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
Item SettingsItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.RootPath + Sitecore.Context.Site.StartItem + "/Settings");

//Google Analytics Tracking can either be Event Tracking or Virtual PageView Tracking – better is Event Tracking
//If "Google Analytics Track PDF Downloads" field is empty in the Settings Item, then consider it as Event Tracking by default
if (SettingsItem != null && !String.IsNullOrEmpty(SettingsItem["Google Analytics Track PDF Downloads"]))
GoogleAnalyticsHitType = SettingsItem["Google Analytics Track PDF Downloads"];
else
GoogleAnalyticsHitType = "event";

//If "Google Analytics PDF Category" field is empty in the Settings Item, then consider "PDF-Downloads" as the category by default
if (SettingsItem != null && !String.IsNullOrEmpty(SettingsItem["Google Analytics PDF Category"]))
GoogleAnalyticsCategory = SettingsItem["Google Analytics PDF Category"];
else
GoogleAnalyticsCategory = "PDF-Downloads";
}
[/code]

Happy Tracking PDF Downloads in Google Analytics! 🙂

3 thoughts on “Tracking PDF Downloads in Google Analytics in a Sitecore Website

  1. I don’t use sitecore. I got this link from search engine results while searching for fetching the values of PDF Downloads in Google Analytics. But as I can see the code, I assume the same code can work with any other Site/CMS which uses Google Analytics and nothing specific to sitecore. Is there anything specific to sitecore here?

    1. John,
      you are absolutely right, there is nothing specific to Sitecore in the PDF Download Tracking code mentioned above, except the Code of C# to fetch the value for HitType and Category. But, you can currently put some static value for it and try, it would work.
      Later, if you want to use the advanced way in your application, update it as required from your code — this is optional, so you can skip it too.

      Thanks for reading and most importantly, getting back to me on this!

      Regards,
      Varun Shringarpure

Leave a Reply

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