3

I'm using Google Analytics to track my pages, and I've added, last week, this code which I've found to try to track my PDF downloads, but this doesn't work :

Link to PDF :

<a href="pdf/my-pdf.pdf"
    onClick="javascript:pageTracker._trackEvent('PDF','Download','My New PDF');
    void(0);">
        PDF
</a>

GA Tracking Code (minified) :

var _gaq=[['_setAccount','UA-XXXXXXXX-XX'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script')); 

Of course, I changed my UA Values for the same of this post.

How can I edit this to allow for file download tracking ?


Edit

<a href="pdf/my-pdf.pdf" target="_blank" onclick="trackLink(event);">PDF</a>

function trackLink(e)
{
    e.preventDefault();
    _gaq.push(['_trackEvent','Download','PDF', e.target.href]); 
    window.setTimeout('location.href="'+e.target.href+'"',100); 
    return false;
}

var _gaq=[['_setAccount','UA-XXXXXXXX-XX'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script')); 

Note: XX's have been added for the purpose of the post and are not in the actual code.

Community
  • 1
  • 1
davewoodhall
  • 998
  • 3
  • 18
  • 43

5 Answers5

2

Okay so a couple things here. Firstly, as gerl pointed out, you are using the wrong GA syntax for the version of the core code you have. So you need to fix your code according to that answer, regardless. But there is another issue to consider: timing.

First, more often than not, the GA code isn't going to have enough time to execute, before the browser redirects to the target URL. There are 2 ways you can get around this: force a timeout of ~100ms before redirect, or make your pdf open up in a separate tab/window.

Personally, I think the latter is a better solution. Since the pdf is loaded into a separate window, you don't need to worry about delaying the redirect to give GA a chance to execute. Also, most people prefer things like pdfs to open up in a separate tab/window, so that they aren't taken away from the page they are on. To do this, add a `target='_blank' to the link:

<a href="pdf/my-pdf.pdf" onclick="_gaq.push(['_trackEvent','Download','PDF', 'pdf/my-pdf.pdf']);" target="_blank">PDF</a>

But if you really want to stick with having the pdf open in the same window/tab, then you will need to force a timeout. I don't like this option as much as the first, because what ~100ms is usually enough time to wait, it's not a guarantee that it's enough time. You can increase the timeout, but the more you do, the longer the visitor has to wait before the redirect occurs, which makes for a bad user experience. But this is one way you could do it:

<a href="pdf/my-pdf.pdf" onclick="trackLink(event);">PDF</a>

<script type="text/javascript">
  function trackLink(e) {
    e.preventDefault();
    _gaq.push(['_trackEvent','Download','PDF', e.target.href]); 
    window.setTimeout('location.href="'+e.target.href+'"',100); 
    return false;
  }

var _gaq=[['_setAccount','UA-XXXXXXXX-XX'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script')); 
</script>

Also note that if you upgrade to universal analytics, that version has timeout/callback funcationality built in to link tracking (that article talks about outbound link tracking but the principle of using the callback function to do the redirect is the same).

CrayonViolent
  • 32,111
  • 5
  • 56
  • 79
  • Very neat and detailed answer; however, when I tried to add your code, nothing happened as the javascript function was blocking any action. – davewoodhall Mar 18 '14 at 20:48
  • @PubliDesign okay, well i actually added my own on-page code in my example (I changed it to show yours). And it works fine for me.. my only guess is that you didn't apply it properly – CrayonViolent Mar 18 '14 at 22:42
  • Ok well I'll see tomorrow when today's stats are all in – davewoodhall Mar 19 '14 at 00:03
  • @PubliDesign are you using a browser addon to see if a GA request is being made onclick? E.g. firebug or dev tools for IE or chrome? Or perhaps a standalone packet sniffer like charles proxy? If you aren't, then use one to see if you see a request firing. If one is not, then you definitely won't be seeing data in your reports. If you are seeing a ping, then...is your account ID right? I see you have lots of XX's in your code.. I *assume* this is for posting sake but you never know. Any filters in place that may be blocking it? – CrayonViolent Mar 19 '14 at 00:43
  • I originally wasn't getting anything in Firebug's console. After doing the latest Firefox update, it does now show a Network Error and I am now redirected to my 404 page. And yes, the GA has been substituted from the generic XX's. Other than changing the XX values, I have nothing different from your code, so I do not see where this is going wrong. Please view post edit. – davewoodhall Mar 19 '14 at 12:10
  • @PubliDesign okay now wait a sec.. your edit shows that you also added `target="_blank"`. If you can do that, then you don't need to have the callback with the timeout. Just put `onclick="_gaq.push(['_trackEvent','Download','PDF', 'pdf/my-pdf.pdf']);"` as your onclick. – CrayonViolent Mar 19 '14 at 13:11
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/50038/discussion-between-publi-design-and-crayon-violent) – davewoodhall Mar 19 '14 at 13:13
0

You have pageTracker instead of _gaq.. Try this instead:

onclick="_gaq.push(['_trackEvent','Download','PDF', 'pdf/my-pdf.pdf']);"
gerl
  • 1,161
  • 2
  • 17
  • 53
  • I'm sorry, this doesn't seem to show up in any of my stats. I'm wondering, do you think it would be "wrong" to link to `my-pdf.php` and use `header(location: the-proper-pdf.pdf)` redirect to my PDF? – davewoodhall Mar 05 '14 at 14:34
  • I edited my solution to add your filename. But your alternative solution might work too. It's just extra work on your end.. – gerl Mar 05 '14 at 15:56
0

Instead of writing a function, you can just add something into the html of the element... perhaps something like this?

<a href="pdf/my-pdf.pdf" onClick="_gaq.push(['_trackEvent', 'PDF','Download','My New PDF']);">

That ought to do it.

I had a similar problem with this sort of thing when trying to decide which type of GA code to use.

This question I posted might help (using ga vs. _gaq.push):

ga or _gaq.push for Google Analytics event tracking?

Community
  • 1
  • 1
Harry Lincoln
  • 614
  • 2
  • 9
  • 30
0
<a href="pdf/my-pdf.pdf" onClick="_gaq.push(['_trackEvent', 'pdf', 'download', 'My New PDF']);">pdf</a>

That should do the job! More info here: https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide

Also, you can always test if your event tracking is working by looking in Real Time Analytics.

Sam Perry
  • 2,554
  • 3
  • 28
  • 29
0

See this link: https://support.google.com/analytics/answer/1136920?hl=en

It shows how to use the hitCallback to help with the issue of the browser redirecting before the event gets pushed.

I think this would be how to modify your code:

<a href="pdf/my-pdf.pdf" onclick="trackLink(event);">PDF</a>

<script type="text/javascript">
    function trackLink(e) {
        e.preventDefault();
        ga('send', 'event', 'Download', 'click', 'PDF', {'hitCallback':
            function () {
                document.location = e.target.href;
            }
        }); 
        return false;
    }

    (function (i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date(); a = s.createElement(o),
        m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
    })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
    ga('create', 'UA-XXXXXXXX-X', 'auto');
    ga('send', 'pageview');
</script>
MB34
  • 4,210
  • 12
  • 59
  • 110