2017-01-23 59 views
0

我想添加到我的网站文件下载与谷歌分析跟踪。谷歌分析 - 跟踪文件下载,无需修改现有链接

我知道我需要为网站上的所有链接添加一个'onclick'事件。
像这样:

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

但我有这么多的链接,因此是不实际的。

有没有办法在同一个地方写任何代码?

谢谢。

+0

你需要添加不同的标签链接,这样您可以识别它们。我不认为你可以在同一时间和相同的标签替换它们。对于WordPress的是这样的https://srd.wordpress.org/plugins/google-analytics-for-wordpress/,也许你可以复制该插件功能。 –

+0

@DincaAdrian - 我的网站不是一个WordPress站点。 – banana

回答

0

你可以做什么,是定义一个全局事件跟踪,您需要与目标=“_空白”目标=“_自我”或与事件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>

+0

它看起来很有趣。 它只适用于jQuery的版本2.1.1?我的网站使用较早的版本... – banana

+0

attributeEndsWith选择器添加在jquery 1.0中,所以你涵盖 – SilentTremor

+0

确定。我被要求调查这个问题, 直到客户决定做这件事需要一段时间...... 当我做到这一点 - 我会尽力实现您的答案,我会继续更新。谢谢! – banana