javascript 在 Google Analytics 中跟踪所有出站链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12302300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Track all outbound links in Google Analytics
提问by Wallace Sidhrée
I've been using a script to track outbound links for a couple of months now. The script WORKS, but in the report generated by Google Analytics many URLs are having a trailing ":80" (default port number) at their end. Read on for more details.
几个月来,我一直在使用脚本来跟踪出站链接。该脚本有效,但在 Google Analytics 生成的报告中,许多 URL 的末尾都有一个尾随“:80”(默认端口号)。请阅读以获得更多详情。
It's maybe important to mention that the website tracking these outbound links has a tremendous amount of outbound traffic (multiply your fantasy by ∞).
值得一提的是,跟踪这些出站链接的网站拥有大量的出站流量(将您的幻想乘以∞)。
The script's purpose
脚本的目的
It tracks ALL outbound links and tag them as "Outbound Links" in Google Analytics.
它跟踪所有出站链接,并在 Google Analytics 中将它们标记为“出站链接”。
The script is heavily commented and has a few instances of console.log() to help debugging (these are kept commented out).
该脚本被大量注释,并且有几个 console.log() 实例来帮助调试(这些都被注释掉了)。
"Outbound Links" show on GA alright, under:
“出站链接”显示在 GA 上,在:
Content > Events > Top Events > "Outbound Links" [click on it] > [report showing all urls clicked]
内容 > 事件 > 热门事件 > “出站链接” [点击它] > [显示所有点击的 url 的报告]
The problem
问题
Under the "Outbound Links" report, where I get all the links that were clicked, I get ":80" at the end of at least 2/3 of all links reported (probably more). GA treats http://example.comand http://example.com:80as different links, separating them in the report. That's of course not desired.
在“出站链接”报告下,我获得了所有被点击的链接,我在报告的所有链接的至少 2/3(可能更多)的末尾得到“:80”。GA 将http://example.com和http://example.com:80视为不同的链接,在报告中将它们分开。这当然不是我们想要的。
Worth mentioning:
值得一提:
Links that end with ":80" always have more hits than their equivalent without ":80", anything from 40% to 60% more hits.
以 ":80" 结尾的链接总是比没有 ":80" 的链接有更多的点击率,点击率高出 40% 到 60%。
The wanted solution
想要的解决方案
- Merge the links that end with ":80" with those without it, OR
- Avoid appending ":80" to links, if possible.
- Bonus: Understand why we get links ending with ":80" at all.
- 将以“:80”结尾的链接与没有它的链接合并,或者
- 如果可能,请避免在链接后附加“:80”。
- 奖励:了解为什么我们会得到以“:80”结尾的链接。
The script
剧本
// Outbound Link Tracking with Google Analytics
// Requires jQuery 1.7 or higher (use .live if using a lower version)
$(function() {
$("a").on('click',function(e){
var url = $(this).attr("href");
// Console logs shows the domain name of the link being clicked and the current window
// console.log('e.currentTarget.host: ' + e.currentTarget.host);
// console.log('window.location.host: ' + window.location.host);
// If the domains names are different, it assumes it is an external link
// Be careful with this if you use subdomains
if (e.currentTarget.host != window.location.host) {
// console.log('external link click');
// Outbound link! Fires the Google tracker code.
_gat._getTrackerByName()._trackEvent("Outbound Links", e.currentTarget.host, url, 0);
// Checks to see if the ctrl or command key is held down
// which could indicate the link is being opened in a new tab
if (e.metaKey || e.ctrlKey) {
// console.log('ctrl or meta key pressed');
var newtab = true;
}
// If it is not a new tab, we need to delay the loading
// of the new link for a just a second in order to give the
// Google track event time to fully fire
if (!newtab) {
// console.log('default prevented');
e.preventDefault();
// console.log('loading link after brief timeout');
setTimeout('document.location = "' + url + '"', 100);
}
}
/*
else {
console.log('internal link click');
}
*/
});
});
采纳答案by Fresheyeball
The reason for the :80
in your output is because of e.currentTarget.host
究其原因,:80
在你的输出是因为e.currentTarget.host
http://www.w3schools.com/jsref/prop_area_host.asp
http://www.w3schools.com/jsref/prop_area_host.asp
I'm not sure why you are tracking that in addition to your already functional url
variable, but you can always insure that :80
is not there with a simple string replace
我不确定为什么除了已经具有功能的url
变量之外还要跟踪它,但是您始终可以:80
通过简单的字符串替换来确保不存在该变量
_gat._getTrackerByName()._trackEvent("Outbound Links", e.currentTarget.host.replace(':80',''), url, 0);
_gat._getTrackerByName()._trackEvent("Outbound Links", e.currentTarget.host.replace(':80',''), url, 0);
回答by Wallace Sidhrée
Fresheyeball answer is the correct one, but because many people have been asking for a completeanswer, I'm going to post the final script with Fresheyeball's contribution.
Fresheyeball 的答案是正确的,但是因为很多人一直在寻求完整的答案,所以我将使用 Fresheyeball 的贡献发布最终脚本。
The short version
简短的版本
// Outbound Link Tracking with Google Analytics
// Wallace Sidhrée - http://dreamyguy.com/
// Requires jQuery 1.7 or higher (use .live if using a lower version)
$(function() {
$("a").on('click',function(e){
var url = $(this).attr("href");
if (e.currentTarget.host != window.location.host) {
_gat._getTrackerByName()._trackEvent("Outbound Links", e.currentTarget.host.replace(':80',''), url, 0);
if (e.metaKey || e.ctrlKey || this.target == "_blank") {
var newtab = true;
}
if (!newtab) {
e.preventDefault();
setTimeout('document.location = "' + url + '"', 100);
}
}
});
});
The complete version (commented and 'debug-able')
完整版本(注释和“可调试”)
// Outbound Link Tracking with Google Analytics
// Wallace Sidhrée - http://dreamyguy.com/
// Requires jQuery 1.7 or higher (use .live if using a lower version)
$(function() {
$("a").on('click',function(e){
var url = $(this).attr("href");
// Console logs shows the domain name of the link being clicked and the current window
// console.log('e.currentTarget.host: ' + e.currentTarget.host);
// console.log('window.location.host: ' + window.location.host);
// If the domains names are different, it assumes it is an external link
// Be careful with this if you use subdomains
if (e.currentTarget.host != window.location.host) {
// console.log('external link click');
// Outbound link! Fires the Google tracker code.
_gat._getTrackerByName()._trackEvent("Outbound Links", e.currentTarget.host.replace(':80',''), url, 0);
// Checks to see if the ctrl or command key is held down
// which could indicate the link is being opened in a new tab
// Also checks if target="_blank" on the link tag which indicates it should always be opened in a new tab
if (e.metaKey || e.ctrlKey || this.target == "_blank")) {
// console.log('ctrl or meta key pressed');
var newtab = true;
}
// If it is not a new tab, we need to delay the loading
// of the new link for a just a second in order to give the
// Google track event time to fully fire
if (!newtab) {
// console.log('default prevented');
e.preventDefault();
// console.log('loading link after brief timeout');
setTimeout('document.location = "' + url + '"', 100);
}
}
/*
else {
console.log('internal link click');
}
*/
});
});
回答by Sébastien Brodeur
The problem with window.open is that the referrer will be lost. A better solution is to use onmousedown instead of onclick. Having done some tests, I know this work better that using window.open or using setTimeout. You got some false positive from people clicking the right mouse button and not choosing "Open in new tab" or "Open in new window", but onclick doesn't always fire for middle and right click on all browser. It's a choice between the lesser of two evils here.
window.open 的问题是引用者会丢失。更好的解决方案是使用 onmousedown 而不是 onclick。做了一些测试后,我知道这项工作比使用 window.open 或使用 setTimeout 更好。您从人们单击鼠标右键而不选择“在新选项卡中打开”或“在新窗口中打开”中得到了一些误报,但是 onclick 并不总是在所有浏览器上进行中键和右键单击时触发。这里是两害相权取其轻的选择。
jQuery(function($){
$('a:not([href*="' + document.domain + '"])').mousedown(function(event){
// Just in case, be safe and don't do anything
if (typeof _gat == 'undefined') {
return;
}
var link = $(this);
var href = link.attr('href');
var noProtocol = href.replace(/http[s]?:\/\//, '');
// Track the event
_gat._getTrackerByName()._trackEvent('Outbound Links', noProtocol);
});
});
回答by Neil McGuigan
use location.hostname instead of location.host . hostname does not include the port.
使用 location.hostname 而不是 location.host 。主机名不包括端口。
回答by Mladen Janjetovic
Here's my solution using Google suggested code
这是我使用Google 建议代码的解决方案
Put this right after your GA tracking code (probably in <head>
)
将此放在您的 GA 跟踪代码之后(可能在<head>
)
// TRACK OUTBOUND LINKS
document.addEventListener("DOMContentLoaded", function() {
var trackOutboundLink = function(url) {
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': function(){document.location = url;}
});
}
var a = document.getElementsByTagName('a');
for(i = 0; i < a.length; i++){
if (a[i].href.indexOf(location.host) == -1 && a[i].href.match(/^http?s:\/\//i)){
a[i].onclick = function(){
trackOutboundLink(this.href);
}
}
}
});
// END
回答by Munjal
This small piece of code worked for me :
这段代码对我有用:
var hostname = window.location.hostname;
jQuery("body a").click(function(){
if(jQuery(this).attr("href").indexOf(hostname)== -1){
ga('send', 'event', {'eventCategory': "Outbound Links", 'eventAction': "OnClick", 'eventLabel': jQuery(this).attr("href")});
}
});
回答by CocaLeaf
Google has an officially supported library that does this stuff for you.
谷歌有一个官方支持的库,可以为你做这些事情。
https://github.com/googleanalytics/autotrack
https://github.com/googleanalytics/autotrack
So your entire Analytics snippet would be something like:
因此,您的整个 Analytics 代码段将类似于:
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
// Replace the following lines with the plugins you want to use.
ga('require', 'eventTracker');
ga('require', 'outboundLinkTracker');
ga('require', 'urlChangeTracker');
// ...
ga('send', 'pageview');
</script>
<script async src="https://www.google-analytics.com/analytics.js"></script>
<script async src="path/to/autotrack.js"></script>