跟踪Google Analytics中的所有出站链接

时间:2012-09-06 14:25:08

标签: javascript jquery google-analytics outbound

我一直在使用脚本来跟踪几个月的出站链接。 脚本工作 ,但在Google Analytics生成的报告中,许多网址的末尾都有一个“80”(默认端口号)。继续阅读以了解更多详情。

可能很重要的是,跟踪这些出站链接的网站有大量的出站流量(将您的幻想乘以∞)。

脚本的目的

它会跟踪所有出站链接并将其标记为Google Analytics中的“出站链接”。

该脚本有很多注释,并且有一些console.log()实例可以帮助调试(这些实例会被注释掉)。

GA上的“出站链接”显示在下面:

内容>活动>热门活动> “出站链接”[点击它]> [显示所有网址点击的报告]

问题

在“出站链接”报告中,我获得了所有点击的链接,在报告的所有链接中至少有2/3结束时得到“:80”(可能更多)。 GA将http://example.comhttp://example.com:80视为不同的链接,在报告中将它们分开。 当然不希望这样。

值得一提:

以“:80”结尾的链接总是比没有“:80”的同等数据更多,点击次数增加40%到60%。

想要的解决方案

  • 将以“:80”结尾的链接与没有它的链接合并,或者
  • 如果可能,请避免在链接中添加“:80”。
  • 奖励:了解为什么我们会得到以“:80”结尾的链接。

脚本

// 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');
        }
        */
    });
});

7 个答案:

答案 0 :(得分:12)

Fresheyeball答案是正确答案,但由于很多人一直在要求完整的答案,我将用Fresheyeball的贡献发布最终剧本。

短版

// 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);
            }
        }
    });
});

完整版(注释和'可调试')

// 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');
        }
        */
    });
});

答案 1 :(得分:5)

输出中:80的原因是e.currentTarget.host

http://www.w3schools.com/jsref/prop_area_host.asp

我不确定为什么除了已经发布的url变量之外还要跟踪它,但是您可以始终确保:80不存在简单的字符串替换

_gat._getTrackerByName()._trackEvent("Outbound Links", e.currentTarget.host.replace(':80',''), url, 0);

答案 2 :(得分:3)

window.open的问题是引用者将丢失。更好的解决方案是使用onmousedown而不是onclick。完成了一些测试后,我知道使用window.open或使用setTimeout可以更好地工作。人们点击鼠标右键并且没有选择“在新标签中打开”或“在新窗口中打开”,你会得到一些误报,但是点击并不总是点击所有浏览器的中间和右键。这是两个邪恶中较小的一个之间的选择。

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);
   });
});

答案 3 :(得分:2)

使用location.hostname而不是location.host。 hostname不包含端口。

答案 4 :(得分:0)

这段小代码对我有用:

    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")});

          }
    });

答案 5 :(得分:0)

Google有一个官方支持的图书馆,可以为您完成这些工作。

https://github.com/googleanalytics/autotrack

因此,您的整个Google代码段将类似于:

<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>

答案 6 :(得分:0)

这是我使用Google suggested code

的解决方案

将您的GA跟踪代码(可能在Accept: application/json

中放好
<head>
相关问题