代码之家  ›  专栏  ›  技术社区  ›  Tom Viner

使用Google Analytics(异步版本)跟踪传出的单击而不破坏target=\u blank

  •  1
  • Tom Viner  · 技术社区  · 15 年前

    我想跟踪用户点击链接到外部网站。我很高兴使用GA的异步版本,因为这允许(在大多数浏览器中)页面继续加载,而不是停留在脚本标记处,等待google-analytics.com/GA.js下载和执行。

    谷歌 recommends 此函数:

    <script type="text/javascript">
    function recordOutboundLink(link, category, action) {
      try {
        var myTracker=_gat._getTrackerByName();
        _gaq.push(['myTracker._trackEvent', ' + category + ', ' + action + ']);
        setTimeout('document.location = "' + link.href + '"', 100)
      }catch(err){}
    }
    </script>
    
    <a href="http://www.example.com" onClick="recordOutboundLink(this, 'Outbound Links', 'example.com');return false;">
    

    这个解决方案的问题是:

    • 它可能需要10毫秒,跟踪事件可能需要300毫秒,但无论发生什么,它都会在100毫秒后更改页面。如果跟踪速度太慢,页面将在被跟踪之前更改。
    • document.location = 意味着原始链接被忽略,因此target=\u blank不会打开新的选项卡/窗口。
    1 回复  |  直到 15 年前
        1
  •  1
  •   Tom Viner    15 年前

    可能的解决方案:

    • 忙着等 ( do {curDate=new Date();} while(curDate-date<millis) )在100毫秒内跟踪有机会发送请求 返回真值 . 坏,因为忙等待占用所有可用的CPU。
    • 使用 window.open 这样就可以打开新的标签页/窗口,这就引出了我当前的最爱:

    • 在单击处理程序中使用 $(this).attr("target", "_blank"); 然后就 return true 在将跟踪命令推到gaq上之后。

    这是因为打开一个新的选项卡会让当前选项卡完成跟踪调用的执行。

    $(document).ready(function(){
      var localserver = document.location.hostname;
      // unfortunately misses if any uppercase used in link scheme
      $("a[href^=http://],a[href^=https://]") 
        .not("a[href^=http://"+localserver+"]")
        .not("a[href^=http://www."+localserver+"]")
        .click(function(e){
            $(this).attr("target", "_blank");
            _gaq.push(['_trackEvent', 
                       'Outgoing Click',
                       $(this).attr("href"),
                       $(this).text()
                     ]);
            return true;
        });
    });
    

    由于总是为外部链接打开一个新选项卡的一个小缺点,我看不到任何其他问题。