Google Analytics(分析) - 在不修改现有链接的情况下跟踪文件下载

时间:2017-01-23 08:45:14

标签: javascript google-analytics

我想通过Google Analytics添加到我的网站文件下载跟踪。

我知道我需要在网站上的所有链接中添加“onclick”事件 像这样:

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

但我有很多链接,所以不实用。

有没有办法在一个地方编写任何代码来执行相同的操作?

感谢。

1 个答案:

答案 0 :(得分:0)

你可以做的是定义一个全局事件跟踪,你需要非常小心target =“_ blank”target =“_ self”或者event.preventdefault()事件,

以下是如何执行此操作,为具有href指定文件扩展名的所有链接附加事件:

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>