javascript 如何扩展谷歌分析以跟踪 AJAX 等(根据 H5BP 文档)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21033205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extend google analytics to track AJAX etc (as per H5BP docs)
提问by alias51
I am trying to install the google analytics augments
identified in the extend.md
file of H5BP (https://github.com/h5bp/html5-boilerplate/blob/v4.3.0/doc/extend.md)
我试图安装google analytics augments
中确定extend.md
H5BP的文件(https://github.com/h5bp/html5-boilerplate/blob/v4.3.0/doc/extend.md)
It states that the "optimised" google analytics JS snippet includes the following code:
它指出“优化的”谷歌分析 JS 代码段包括以下代码:
var _gaq = [['_setAccount', 'UA-XXXXX-X'], ['_trackPageview']];
and that additional augments such as track jquery AJAX requests
, track javascript errors
and track page scroll
should be added after _gaq
is defined.
并且应该在定义之后添加 额外的增强,例如track jquery AJAX requests
,track javascript errors
和。track page scroll
_gaq
In fact, the snippet included with the current version of H5BP does not make reference to _gaq
as a variable:
事实上,当前版本的 H5BP 中包含的代码片段并没有将其_gaq
作为变量引用:
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X');ga('send','pageview');
This creates an undefined error when trying to use any of the H5BP extensions. E.g.
当尝试使用任何 H5BP 扩展时,这会产生未定义的错误。例如
if (typeof _gaq !== "undefined" && _gaq !== null) {
$(document).ajaxSend(function(event, xhr, settings){
_gaq.push(['_trackPageview', settings.url]);
});
}
Will not work as _gaq is not defined.
不会工作,因为 _gaq 未定义。
How are these augments intended to be implemented? Can someone provide a working example showing a full implementation of all the extensions?
这些增强功能打算如何实施?有人可以提供一个工作示例,显示所有扩展的完整实现吗?
Thanks
谢谢
采纳答案by artfuldev
The code you are trying to add will not work, as _gaq
was an array used to push the tracking beacons to in the older Google Analytics (GA) version. But the HTML5 BoilerPlate (H5BP), in its latest version you seem to be using, has updated itself to make use of Universal Analytics (UA), the next version of GA which Google has released. This can be seen from the protocol-relative URL //www.google-analytics.com/analytics.js
and also the docs for the latest version. Unfortunately, it seems the doc you mentionedhasn't been updated, as the link given at the H5BP for the sourceof the optimised GA code, has itself been updated with code for UAand that is what the H5BP source is now using.
您尝试添加的代码将不起作用,因为_gaq
在较旧的 Google Analytics (GA) 版本中用于将跟踪信标推送到的数组也是如此。但是 HTML5 BoilerPlate (H5BP),在您似乎正在使用的最新版本中,已经更新自身以使用 Universal Analytics (UA),Google 发布的下一个 GA 版本。这可以从协议相关的 URL//www.google-analytics.com/analytics.js
以及最新版本的文档中看到。不幸的是,您提到的文档似乎尚未更新,因为在 H5BP 上提供的优化 GA 代码源链接本身已使用UA代码进行了更新,而这正是 H5BP 源现在正在使用的。
Consequently, your additional source code extending the use of the _gaq
object will not work, as you are not using ga.js
which has functions to process the data pushed to the _gaq
object from GA, but the analytics.js
for UA, which does not initialise any such object as _gaq
or have functions to process the data pushed to _gaq
.
因此,您扩展_gaq
对象使用的附加源代码将不起作用,因为您没有使用ga.js
which 具有处理_gaq
从 GA推送到对象的数据的函数,而是使用analytics.js
for UA,它不会将任何此类对象初始化为_gaq
或具有函数来处理推送到的数据_gaq
。
But, before upgrading itself to use analytics.js
(UA), H5BP had a GA version of the script, like this (I got this, courtesy of a friend who used to work with H5BP):
但是,在升级自己使用analytics.js
(UA)之前,H5BP 有一个 GA 版本的脚本,像这样(我得到了这个,由一个曾经使用 H5BP 的朋友提供):
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']]; //here the _gaq was initialised
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src='//www.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
Ideally, this should replace the lines of code you mentioned, namely
理想情况下,这应该替换您提到的代码行,即
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X');ga('send','pageview');
If you did that, then your use of the code
如果你这样做了,那么你对代码的使用
if (typeof _gaq !== "undefined" && _gaq !== null) {
$(document).ajaxSend(function(event, xhr, settings){
_gaq.push(['_trackPageview', settings.url]);
});
}
and so on which use _gaq
will work.
等等哪个使用_gaq
将起作用。
Also remember that the H5BP code you are currently using is best, as Google is phasing out GA in a move to make Universal Analytics the future of analytics. The older code I have mentioned no longer works (or will stop working in the near future, depending on Google). Read more about this at UA Upgrade Center.
另请记住,您当前使用的 H5BP 代码是最好的,因为 Google 正在逐步淘汰 GA,以使 Universal Analytics 成为分析的未来。我提到的旧代码不再有效(或将在不久的将来停止工作,具体取决于 Google)。在UA 升级中心阅读更多相关信息。
Keep in mind that the current H5BP uses UA (analytics.js) code which is an optimised form of what Google provides, as found here.
请记住,目前H5BP采用UA(analytics.js)的代码是什么谷歌提供了一个优化的形式,如发现在这里。
That explains why the scripts mentioned in extend.md
won't work on the H5BP you seem to be working on, an a possible workaround by implementing the old code. What you need is a way to track AJAX etc. with the script you do have in place. For that, each time an AJAX request completes, you can simply record a virtual pageview.You can find a similar scenario here. There the asker applies the tracking to the opening of a modal. You can apply the same technique to track AJAX calls and retreives of a page or partial page. The VURLas I've specified in the answer can be, in your case, /virtual/ajax/url-of-page-retrieved-via-ajax
.
这解释了为什么 中提到的脚本extend.md
不适用于您似乎正在处理的 H5BP,这是一种通过实现旧代码的可能解决方法。您需要的是一种使用现有脚本跟踪 AJAX 等的方法。为此,每次 AJAX 请求完成时,您只需记录一次虚拟浏览量即可。您可以在此处找到类似的场景。在那里提问者将跟踪应用于模态的打开。您可以应用相同的技术来跟踪页面或部分页面的 AJAX 调用和检索。我在答案中指定的VURL在您的情况下可以是/virtual/ajax/url-of-page-retrieved-via-ajax
.
If you do not wish to send virtual pageviews, you can also send customised events for each AJAX request. Read more about event tracking in UA here.
如果您不想发送虚拟浏览量,您还可以为每个 AJAX 请求发送自定义事件。在此处阅读有关 UA 中事件跟踪的更多信息。
If you want to know what the arguments of the function you specified stand for, you can read here. This is where the script in the extend.md
file you mentioned was taken. An attempt to modify the script for use with UA would probably look like this:
如果你想知道你指定的函数的参数代表什么,你可以在这里阅读。这是extend.md
您提到的文件中的脚本的位置。修改脚本以用于 UA 的尝试可能如下所示:
(function ($) {
// Log all jQuery AJAX requests to Google Analytics
$(document).ajaxSend(function(event, xhr, settings){
ga('send','pageview',settings.url.pathname);
});
})(jQuery);
The ajaxSend()
method is a callback which is fired every time a jQuery AJAX call is completed. Remember the word jQuery
here. This only works for jQuery AJAX requests. xhr
generally stands for XMLHttpRequest. I think it assumes one knows what a jQuery AJAX call is, I'm not very knowledgeable about that.
该ajaxSend()
方法是每次完成 jQuery AJAX 调用时都会触发的回调。记住jQuery
这里的词。这仅适用于 jQuery AJAX 请求。xhr
通常代表 XMLHttpRequest。我认为它假设人们知道 jQuery AJAX 调用是什么,我对此不是很了解。
To track Javascript errors using UA, a similar script would be:
要使用 UA 跟踪 Javascript 错误,类似的脚本将是:
(function(window){
var undefined,
link = function (href) {
var a = window.document.createElement('a');
a.href = href;
return a;
};
window.onerror = function (message, file, line, column) {
var host = link(file).hostname;
ga('send','event',
(host == window.location.hostname || host == undefined || host == '' ? '' : 'external ') + 'error',
message, file + ' LINE: ' + line + (column ? ' COLUMN: ' + column : ''),
{'nonInteraction': 1});
};
}(window));
This collects likewise: Event Category will be host+error
, Action will be the error message, and label will point to where the error occurred (line no, filename, etc.).
这同样收集:事件类别将是host+error
,操作将是错误消息,标签将指向错误发生的位置(行号、文件名等)。
Tracking page scroll is also very similar:
跟踪页面滚动也很相似:
$(function(){
var isDuplicateScrollEvent,
scrollTimeStart = new Date,
$window = $(window),
$document = $(document),
scrollPercent;
$window.scroll(function() {
scrollPercent = Math.round(100 * ($window.height() + $window.scrollTop())/$document.height());
if (scrollPercent > 90 && !isDuplicateScrollEvent) { //page scrolled to 90%
//If you want to track for page scroll for some other percentage of scroll, you
//can edit the number 90, or write additional conditional ga('send',...) calls
//inside this block and vary the label accordingly, specifying the percentage
//of scroll.
isDuplicateScrollEvent = 1;
ga('send','event','scroll',
'Window: ' + $window.height() + 'px; Document: ' + $document.height() + 'px; Time: ' + Math.round((new Date - scrollTimeStart )/1000,1) + 's',
{'nonInteraction':1}
);
}
});
});
Here, Event Category will be scroll
, Action will be thw Window, height and document, and time. If you want to track scroll as an interactive event (which means if you want a user to be tracked as a non-bounce user if he scrolls) you can remove the line {'nonInteraction':1}
在这里,事件类别将是scroll
,动作将是窗口、高度和文档以及时间。如果您想将滚动跟踪为交互式事件(这意味着如果您希望用户在滚动时被跟踪为非弹跳用户),您可以删除该行{'nonInteraction':1}
Hope that helps! :)
希望有帮助!:)
回答by dr0zd
I have several ajax calls on my site. With Google Analytics Universal I use
我的网站上有几个 ajax 调用。我使用 Google Analytics Universal
$.ajax({
...
success: function (data) {
ga('send','pageview','/virtual/....');
},
...
});
Using of /virtual/
makes filtering easier if I want to separate date with or without ajax calls
/virtual/
如果我想在有或没有 ajax 调用的情况下分隔日期,使用 of会使过滤更容易