如何扩展谷歌分析以跟踪AJAX等(根据H5BP文档)

时间:2022-01-15 14:01:52

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)

我正在尝试安装扩展中识别的谷歌分析增强。H5BP的md文件(https://github.com/h5bp/html5-erplate/docb/v4.3.0/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.

在定义了_gaq之后,应该添加一些额外的扩展,比如跟踪jquery AJAX请求、跟踪javascript错误和跟踪页面滚动。

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

谢谢

2 个解决方案

#1


8  

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 mentioned hasn't been updated, as the link given at the H5BP for the source of the optimised GA code, has itself been updated with code for UA and that is what the H5BP source is now using.

您试图添加的代码将不起作用,因为在旧的谷歌分析(GA)版本中,_gaq是一个用于将跟踪信标推送到跟踪信标的数组。但是在你似乎正在使用的最新版本中,HTML5样板文件(H5BP)已经利用谷歌发布的下一个GA版本Universal Analytics (UA)对自己进行了升级。这可以从协议相关的URL //www.google-analytics.com/analytics.js和最新版本的文档中看到。不幸的是,您提到的doc似乎没有被更新,因为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。它具有处理从GA推送到_gaq对象的数据的函数,但是是分析。用于UA的js,它不会初始化任何这样的对象,比如_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):

但是,在升级到使用分析之前。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代码是最好的,因为谷歌正在逐步淘汰GA,以使Universal Analytics成为分析的未来。我提到的旧代码不再工作了(或者将在不久的将来停止工作,取决于谷歌)。在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 VURL as I've specified in the answer can be, in your case, /virtual/ajax/url-of-page-retrieved-via-ajax.

这就解释了为什么扩展中提到的脚本。md无法处理您似乎正在处理的H5BP,通过实现旧代码,这是一个可能的解决方案。您需要的是一种使用已有脚本跟踪AJAX等的方法。为此,每次AJAX请求完成时,您可以简单地记录一个虚拟页面视图。您可以在这里找到类似的场景。在那里,请求者将跟踪应用到一个模式的开始。您可以应用相同的技术来跟踪页面或部分页面的AJAX调用和retreives。我在答案中指定的VURL可以是,在您的情况下,/虚拟/ajax/url-检索-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请求发送定制的事件。请在这里阅读更多有关事件跟踪的信息。

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:

如果您想知道指定函数的参数表示什么,可以在这里阅读。这就是扩展中的脚本。你提到的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.).

这同样收集:事件类别将是主机+错误,操作将是错误消息,标签将指向错误发生的地方(行号、文件名等)。

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}

在这里,事件类别将是滚动,动作将是thw窗口,高度和文件,和时间。如果希望将滚动条作为交互事件进行跟踪(这意味着如果希望将用户作为非反弹用户进行跟踪(如果用户滚动的话),可以删除行{'nonInteraction':1}

Hope that helps! :)

希望会有帮助!:)

#2


6  

I have several ajax calls on my site. With Google Analytics Universal I use

我的站点上有几个ajax调用。我使用谷歌分析通用

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

如果我想用ajax调用或不使用ajax调用来分离日期,使用/virtual/使过滤更加容易

#1


8  

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 mentioned hasn't been updated, as the link given at the H5BP for the source of the optimised GA code, has itself been updated with code for UA and that is what the H5BP source is now using.

您试图添加的代码将不起作用,因为在旧的谷歌分析(GA)版本中,_gaq是一个用于将跟踪信标推送到跟踪信标的数组。但是在你似乎正在使用的最新版本中,HTML5样板文件(H5BP)已经利用谷歌发布的下一个GA版本Universal Analytics (UA)对自己进行了升级。这可以从协议相关的URL //www.google-analytics.com/analytics.js和最新版本的文档中看到。不幸的是,您提到的doc似乎没有被更新,因为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。它具有处理从GA推送到_gaq对象的数据的函数,但是是分析。用于UA的js,它不会初始化任何这样的对象,比如_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):

但是,在升级到使用分析之前。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代码是最好的,因为谷歌正在逐步淘汰GA,以使Universal Analytics成为分析的未来。我提到的旧代码不再工作了(或者将在不久的将来停止工作,取决于谷歌)。在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 VURL as I've specified in the answer can be, in your case, /virtual/ajax/url-of-page-retrieved-via-ajax.

这就解释了为什么扩展中提到的脚本。md无法处理您似乎正在处理的H5BP,通过实现旧代码,这是一个可能的解决方案。您需要的是一种使用已有脚本跟踪AJAX等的方法。为此,每次AJAX请求完成时,您可以简单地记录一个虚拟页面视图。您可以在这里找到类似的场景。在那里,请求者将跟踪应用到一个模式的开始。您可以应用相同的技术来跟踪页面或部分页面的AJAX调用和retreives。我在答案中指定的VURL可以是,在您的情况下,/虚拟/ajax/url-检索-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请求发送定制的事件。请在这里阅读更多有关事件跟踪的信息。

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:

如果您想知道指定函数的参数表示什么,可以在这里阅读。这就是扩展中的脚本。你提到的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.).

这同样收集:事件类别将是主机+错误,操作将是错误消息,标签将指向错误发生的地方(行号、文件名等)。

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}

在这里,事件类别将是滚动,动作将是thw窗口,高度和文件,和时间。如果希望将滚动条作为交互事件进行跟踪(这意味着如果希望将用户作为非反弹用户进行跟踪(如果用户滚动的话),可以删除行{'nonInteraction':1}

Hope that helps! :)

希望会有帮助!:)

#2


6  

I have several ajax calls on my site. With Google Analytics Universal I use

我的站点上有几个ajax调用。我使用谷歌分析通用

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

如果我想用ajax调用或不使用ajax调用来分离日期,使用/virtual/使过滤更加容易