设置Google Analytics以跟踪多个代码段?

时间:2013-10-27 01:02:46

标签: javascript google-analytics google-analytics-api

我做了一个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?

2 个答案:

答案 0 :(得分:2)

跟进@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');

答案 1 :(得分:1)

阅读documentation,正确的语法是:

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

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

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

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