篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Google Analytics出站链接跟踪相关的知识,希望对你有一定的参考价值。
/**
* Outbound link tracking
* -------------------------
*/
(function($) {
// JS redirect function (because window.location doesnt add the referrer in the request header)
function goTo(url, newtab) {
var a = document.createElement("a");
if(!a.click) //for IE
{
window.location = url;
return;
}
a.setAttribute('href', url);
a.style.display = 'none';
if (newtab) a.setAttribute('target', '_blank');
document.body.appendChild(a);
a.click();
}
// attach on click event listener to all <a> elements
$('a:not(.js-no-tracking)').on('click', function(e) {
var url = $(this).attr('href');
var sending = false;
// abandon if link already aborted or analytics is not available
if (e.isDefaultPrevented() || typeof ga !== 'function') return;
if (e.currentTarget.hostname != window.location.hostname && !url.match(/^javascript\:/i)) {
if (e.ctrlKey || e.shiftKey || e.metaKey || e.which == 2 || this.target == "_blank") {
var newtab = true;
}
if (newtab) {
// don't prevent link navigation for new tab links
ga(
'send', 'event', 'outbound link', 'click', url
);
} else {
// for links that don't open in a new tab, navigate with JS after GA event has been sent out
e.preventDefault ? e.preventDefault() : e.returnValue = !1;
sending = true;
//if after 300 ms the GA data still didnt get sent, redirect manually
setTimeout(function() {
if (sending) { goTo(url); }
}, 300);
ga(
'send', 'event', 'outbound link', 'click', url,
{
'hitCallback': function() {
sending = false;
goTo(url);
}
}
);
}
}
});
})(jQuery);
以上是关于javascript Google Analytics出站链接跟踪的主要内容,如果未能解决你的问题,请参考以下文章