【问题标题】:Track all outbound links in Google Analytics跟踪 Google Analytics 中的所有出站链接
【发布时间】:2012-09-06 14:25:08
【问题描述】:

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

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

脚本的目的

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

该脚本有大量注释,并且有一些 console.log() 实例来帮助调试(这些都被注释掉了)。

“出站链接”显示在 GA 上,如下:

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

问题

在“出站链接”报告下,我得到了所有被点击的链接,我在报告的所有链接的至少 2/3(可能更多)的末尾得到“:80”。 GA 将 http://example.com 和 http://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');
        }
        */
    });
});

【问题讨论】:

  • 非常有价值。请考虑为后代显示编辑后的代码。

标签: javascript jquery google-analytics outbound


【解决方案1】:

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

【讨论】:

  • Ctrl键检测是否也会检测到链接是否点击了鼠标中轮?
【解决方案2】:

您的输出中出现: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);

【讨论】:

  • 如您所见,该函数包含 all 锚标签,因此我需要有一个“防呆”条件来将链接中的 url 与当前的 url 进行比较领域。这就是使用if (e.currentTarget.host != window.location.host) 背后的想法。我仍然需要进行该检查 - 或类似的检查 - 因为这是确保 Google Analytics 中的事件跟踪仅在链接指向当前域之外时发生的唯一方法。但感谢您指出正确的方向。明天我会推送更改,并在测试后立即批准您的回复。 ;)
  • "一经测试就批准您的回复"
  • 我发现你的回答只是部分正确。这是因为“或”之后的内容不正确——考虑到我们想要在 GA 中分配类别、动作和标签的方式。我们不希望操作与标签相同,如果我们使用e.currentTarget.href 或$(this).attr("href") 作为操作,就会发生这种情况。使用e.currentTarget.host.replace(':80',''),我们仅将域作为操作www.example.com 获得,这对我们非常有用。参考Google Analytics Event Tracking Guide.
  • 编辑你的答案,我会批准它;)
【解决方案3】:

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

【讨论】:

  • window.open 并不总是省略引荐来源网址:stackoverflow.com/questions/4762254/…
  • “mousedown”的主要问题是它在某些触摸屏上不起作用。
  • “一些触摸屏”,你能说得更具体点吗?
【解决方案4】:

使用 location.hostname 而不是 location.host 。主机名不包括端口。

【讨论】:

    【解决方案5】:

    这小段代码对我有用:

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

    【讨论】:

      【解决方案6】:

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

      https://github.com/googleanalytics/autotrack

      因此,您的整个 Analytics sn-p 将类似于:

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

      【讨论】:

        【解决方案7】:

        这是我使用Google suggested code的解决方案

        将其放在您的 GA 跟踪代码之后(可能在 &lt;head&gt; 中)

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-29
          • 2013-04-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多