0
votes

I want to add to my site file downloads tracking with Google Analytics.

I understand that I need to add an 'onclick' event to all the links on the site.
Like this:

<a href="file.pdf" onclick="ga('send', 'event', 'Google Link', 'Action
label', 'Action Value');">link</a>

But I have so many links so it is not practical.

Is there a way to write any code in one place which will do the same thing?

Thanks.

1
you need to add a different label for links so you can recognize them. I don't think you can replace them in the same time and with the same label. for wordpress is something like this srd.wordpress.org/plugins/google-analytics-for-wordpress , maybe you can replicate that pluggin functionality. - Dinca Adrian
@DincaAdrian - My site is not a wordpress site. - banana

1 Answers

0
votes

What you can do, is to define a global event tracking, you need to be extremely careful with target="_blank" target="_self" or with event.preventdefault() on events,

Here is how you can do it, attaching event for all links having in href specified file extensions:

console.clear();
(function ($) {
    var filesExtensions = ['.pdf', '.docx', '.xsls', '.jpg'];
    //attach event for each file
    filesExtensions.forEach(function (element) {
        //http://api.jquery.com/attribute-ends-with-selector/
        //why mouse down? becouse a link can have target _blank or some other preventdefault or stopPropagation on click event defined
        //you can use click, but you might face some problems
        $("a[href$='" + element + "']").mousedown(function (event) {
            pushDownload(event.target);
        });
        //prevent event propagation (stack overflow will show ugly server error at link navigation)
        //this click event is not part of implemntation
        //TODO: remove on your website
        $("a[href$='" + element + "']").click(function (event) {
            event.preventDefault();
        });
    });

    function pushDownload(target) {
        var eventCategory = "Files";
        var eventAction = "Download";
        var eventLabel = getFileName($(target).attr('href'));
        console.log("ga('send', 'event', '" + eventCategory + "', '" + eventAction + "','" + eventLabel + '");');
        if (window.ga && ga.loaded) {
            ga('send', 'event', eventCategory, eventAction, eventLabel);
        }
        else {
            console.error("Exception: ga undefined");
        }
    };

    function getFileName(str) {
        return str.substr(str.lastIndexOf("/") + 1);
    };
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="file.pdf">file.pdf download</a><br>
<a href="file.docx">file.docx download</a><br>
<a href="/invoices/invoice.pdf">invoice.pdf download</a>