设置谷歌分析以跟踪多个代码段

Setting up Google Analytics to track multiple snippets?

本文关键字:代码 跟踪 谷歌 设置      更新时间:2023-09-26

我做了一个JS小提琴来演示这个问题:http://jsfiddle.net/8uC4Z/1/

为什么 ga.getAll() 只有一个跟踪器而不是两个?我正在按照这里的说明进行操作:https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced

/* https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced */
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-42441200-1', 'domain1');
ga('send', 'pageview'); // first one created is the default
ga('create', 'UA-35320164-1 ', 'domain2');
ga('domain2.send', 'pageview');
ga(function() {
    console.log("The following is the array of all trackers:");
    console.log(ga.getAll());
    console.log("Why is there only 1 in the array?");
}); // why only 1 snippet?

跟进@Steven V的回答...

只能有一个未命名(默认)跟踪器。当第三个参数是字符串时:

ga('create', 'UA-42441200-1', 'domain1');

我猜这是设置跟踪器cookieDomain的快捷方式,而不是跟踪器名称。

您可以使用第一个跟踪器的快捷方式代码,但必须明确命名第二个跟踪器:

ga('create', 'UA-42441200-1', 'domain1');
ga('send', 'pageview'); // first one created is the default
ga('create', 'UA-35320164-1', {'name': 't2'});
ga('t2.send', 'pageview');

阅读文档,正确的语法是:

ga('create', 'UA-12345-6', {'name': 'newTracker'});

其中第三个参数是对象,而不是字符串。

ga('create', 'UA-42441200-1', {'name': 'domain1'});
ga('create', 'UA-35320164-1 ', {'name': 'domain2'});

ga.getAll()返回两个对象对我有用。