如何让谷歌分析跟踪由AJAX调用的页面?

时间:2022-09-30 15:16:54

I am calling a page on my website using AJAX but for some reason Google Analytics is not registering the page visit. Do I have to do something to force it to register AJAX triggered pages?

我正在用AJAX调用我的网站上的一个页面,但是出于某种原因,谷歌Analytics并没有注册页面访问。我需要做些什么来迫使它注册AJAX引发的页面吗?

I am using the latest Universal anaytics code as follows:

我正在使用最新的通用anaytics代码如下:

<script>
  (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-XXXXXXXX-1', 'mywebsite.ext');
  ga('send', 'pageview');

</script>

I am using a JQuery AJAX call to the page containing the above snippet as follows:

我正在对包含上述代码片段的页面使用JQuery AJAX调用,如下所示:

<script>
//<![CDATA[             
$(document).ready(function(){

        $.ajax({
                url : "http://www.mywebsite.ext",
                type: "GET",
                async: false,
                data : { fromajax : "y" },
                success: function(data, textStatus, jqXHR)
                {
                        // alert("success - Data: " + data + "\ntextStatus: " + textStatus);
                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                        alert("error \ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown + "\njqXHR: " + jqXHR);
                }
        });

});
//]]>

I am certain the page is being called as I have some logging statements writing to a database. I also know the Analytics code is working as I am testing it using the real time overview.

我确信正在调用该页,因为我有一些日志语句写入数据库。我也知道分析代码在工作,因为我正在使用实时概述测试它。

So to summarise, I have a page calling http://www.mywebsite.ext using AJAX and the destination page (http://www.mywebsite.ext) contains some Universal Analytics code which does not appear to track the page. If you visit the page normally from your browser the page is tracked fine.

总之,我有一个页面使用AJAX调用http://www.mywebsite.ext,目标页面(http://www.mywebsite.ext)包含一些通用的分析代码,这些代码看起来并没有跟踪页面。如果您通常从您的浏览器访问页面,页面会被跟踪。

I have since discovered from the thread that I can call the "ga" function with a virtual folder. I have therefore done away with the AJAX call and instead modified the Universal Analytics as follows:

我从线程中发现,我可以使用一个虚拟文件夹调用“ga”函数。因此,我不再使用AJAX调用,而是修改了Universal Analytics,如下所示:

<script>
(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-XXXXXXXX-1', 'mywebsite.ext');
ga('send', 'pageview', '/localfolder/page');
ga('send', 'pageview');

</script>

The problem I have now is that it calls ga('send', 'pageview', '/localfolder/page'); but not ga('send', 'pageview');

我现在遇到的问题是它调用ga('send'、'pageview'、'/localfolder/page');但不是ga(“发送”,“页面”);

But I understand there is a minimum interval between events: Google Analytics Event Tracking - Minimal Interval between the events

但我知道事件之间有一个最小间隔:谷歌分析事件跟踪——事件之间的最小间隔

I therefore added a setTimeout(function(){},2000); between events and the last event is still not called. I even went up to 9 seconds.

因此,我添加了一个setTimeout(function(){},2000);事件和最后一个事件之间仍然没有调用。我甚至用了9秒。

4 个解决方案

#1


20  

The old standard for loading Google Analytics was the asynchronous method:

加载谷歌分析的旧标准是异步方法:

var _gaq=[["_setAccount","UA-#######-#"],["_trackPageview"]];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=("https:"==location.protocol?"//ssl":"//www")+".google-analytics.com/ga.js";
s.parentNode.insertBefore(g,s)}(document,"script"));

That bit tracks the initial page load but not subsequent AJAX calls. Any time you want to track a page load, place add the following snippet:

该位跟踪初始页面加载,但不跟踪后续的AJAX调用。当您想要跟踪页面加载时,请添加以下代码片段:

// "_trackEvent" is the pageview event, 
_gaq.push(['_trackPageview', '/some-page']);

_trackPageview is used again but this time we provide the URL of the AJAX address that was loaded. Using the small JavaScript snippet above allows you to keep track of pageviews just as you would if the entire page reloaded. I'd recommend using this snippet with MooTools' History plugin.

再次使用_trackPageview,但是这次我们提供了加载的AJAX地址的URL。使用上面的小JavaScript代码片段,您可以跟踪页面视图,就像您在重新加载整个页面时所做的那样。我推荐使用MooTools的History插件。

Combined with Ajax, your code should be similiar to this:

结合Ajax,您的代码应该与以下内容相似:

jQuery(document).ajaxComplete(function(e, xhr, settings){
  var d = document.location.pathname + document.location.search + document.location.hash;
  _gaq.push(['_trackPageview', d]);
});

If you want to use the Universal Analytics Code, the syntax for virtual pageloads is different.

如果您想使用Universal Analytics代码,那么虚拟页面加载的语法是不同的。

This is the syntax for tracking virtual pageviews in UA:

这是在UA中跟踪虚拟页面视图的语法:

ga(‘send’, ‘pageview’, ‘path to your virtual page’);

Examples:

例子:

<a href=”http://www.example.com/gu/dw/seo-beginners-guide.pdf” onClick=”ga(‘send’, ‘pageview’, ‘/virtual/guides/download/seo-beginners-guide.pdf’);”> Download SEO Beginners Guide</a> 

So when a user clicks on the link ‘Download SEO Beginners Guide’, UA will generate a virtual pageview called ‘/virtual/guides/download/seo-beginners-guide.pdf’.

因此,当用户点击“下载SEO初学者指南”链接时,UA将生成一个名为“/virtual/ Guide / Download / SEO - Beginners - Guide .pdf”的虚拟页面视图。

Sources:
http://davidwalsh.name/ajax-analytics
https://*.com/a/7762559/3582159
http://www.optimizesmart.com/event-tracking-guide-google-analytics-simplified-version/

来源:http://davidwalsh.name/ajax-analytics https://*.com/a/7762559/3582159 https://*.com/a/7762559/3582159

#2


1  

Html

<a class="ajax-load" href="home.html" >Home</a>

Javascript

jQuery(document).ready(function($) {
    $(".ajax-load").click(function(event) {
        event.preventDefault();
        var href = $(this).attr("href");
        $.ajax({
            url: href,
            type: 'post',
            dataType: 'html',

        })
        .done(function(response) {
            $(".somediv").html(response);
            // now send page view
            ga('send','pageview','/virtual/....');
        })
        .fail(function() {
            // show error dialog
        })
    });
});

#3


0  

You may have problems because those receiving Ajax are not expecting or processing Javascript.

您可能会遇到问题,因为接收Ajax的人并不期望或处理Javascript。

Google has this protocol as a solution:

谷歌有以下协议作为解决方案:

POST /collect HTTP/1.1 Host: www.google-analytics.com

发布/收集HTTP/1.1主机:www.google-analytics.com

payload_data

payload_data

details are here:

细节是:

https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#proxy-server-tracking

https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide proxy-server-tracking

You will need to use a POST or GET method using your scripting language. If you come up with an answer and working solution, please let me know! I'm doing all I can to get this to work.

您将需要使用POST或GET方法使用脚本语言。如果你有一个答案和工作方案,请让我知道!我尽我所能让这一切正常运转。

#4


-1  

I recommend using another service for AJAX analytics: http://discrete.li/

我建议使用另一个服务进行AJAX分析:http://discrete te.li/

It automatically gives you stats on all ajax requests, much like google analytics automatically gives you page stats. No need to manually call the service on each success function. Plus, it gives you informations on errors, latency, and full payload logs.

它自动提供所有ajax请求的统计信息,就像谷歌分析自动提供页面统计信息一样。无需手动调用每个成功函数上的服务。此外,它还提供关于错误、延迟和完整有效负载日志的信息。

#1


20  

The old standard for loading Google Analytics was the asynchronous method:

加载谷歌分析的旧标准是异步方法:

var _gaq=[["_setAccount","UA-#######-#"],["_trackPageview"]];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=("https:"==location.protocol?"//ssl":"//www")+".google-analytics.com/ga.js";
s.parentNode.insertBefore(g,s)}(document,"script"));

That bit tracks the initial page load but not subsequent AJAX calls. Any time you want to track a page load, place add the following snippet:

该位跟踪初始页面加载,但不跟踪后续的AJAX调用。当您想要跟踪页面加载时,请添加以下代码片段:

// "_trackEvent" is the pageview event, 
_gaq.push(['_trackPageview', '/some-page']);

_trackPageview is used again but this time we provide the URL of the AJAX address that was loaded. Using the small JavaScript snippet above allows you to keep track of pageviews just as you would if the entire page reloaded. I'd recommend using this snippet with MooTools' History plugin.

再次使用_trackPageview,但是这次我们提供了加载的AJAX地址的URL。使用上面的小JavaScript代码片段,您可以跟踪页面视图,就像您在重新加载整个页面时所做的那样。我推荐使用MooTools的History插件。

Combined with Ajax, your code should be similiar to this:

结合Ajax,您的代码应该与以下内容相似:

jQuery(document).ajaxComplete(function(e, xhr, settings){
  var d = document.location.pathname + document.location.search + document.location.hash;
  _gaq.push(['_trackPageview', d]);
});

If you want to use the Universal Analytics Code, the syntax for virtual pageloads is different.

如果您想使用Universal Analytics代码,那么虚拟页面加载的语法是不同的。

This is the syntax for tracking virtual pageviews in UA:

这是在UA中跟踪虚拟页面视图的语法:

ga(‘send’, ‘pageview’, ‘path to your virtual page’);

Examples:

例子:

<a href=”http://www.example.com/gu/dw/seo-beginners-guide.pdf” onClick=”ga(‘send’, ‘pageview’, ‘/virtual/guides/download/seo-beginners-guide.pdf’);”> Download SEO Beginners Guide</a> 

So when a user clicks on the link ‘Download SEO Beginners Guide’, UA will generate a virtual pageview called ‘/virtual/guides/download/seo-beginners-guide.pdf’.

因此,当用户点击“下载SEO初学者指南”链接时,UA将生成一个名为“/virtual/ Guide / Download / SEO - Beginners - Guide .pdf”的虚拟页面视图。

Sources:
http://davidwalsh.name/ajax-analytics
https://*.com/a/7762559/3582159
http://www.optimizesmart.com/event-tracking-guide-google-analytics-simplified-version/

来源:http://davidwalsh.name/ajax-analytics https://*.com/a/7762559/3582159 https://*.com/a/7762559/3582159

#2


1  

Html

<a class="ajax-load" href="home.html" >Home</a>

Javascript

jQuery(document).ready(function($) {
    $(".ajax-load").click(function(event) {
        event.preventDefault();
        var href = $(this).attr("href");
        $.ajax({
            url: href,
            type: 'post',
            dataType: 'html',

        })
        .done(function(response) {
            $(".somediv").html(response);
            // now send page view
            ga('send','pageview','/virtual/....');
        })
        .fail(function() {
            // show error dialog
        })
    });
});

#3


0  

You may have problems because those receiving Ajax are not expecting or processing Javascript.

您可能会遇到问题,因为接收Ajax的人并不期望或处理Javascript。

Google has this protocol as a solution:

谷歌有以下协议作为解决方案:

POST /collect HTTP/1.1 Host: www.google-analytics.com

发布/收集HTTP/1.1主机:www.google-analytics.com

payload_data

payload_data

details are here:

细节是:

https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#proxy-server-tracking

https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide proxy-server-tracking

You will need to use a POST or GET method using your scripting language. If you come up with an answer and working solution, please let me know! I'm doing all I can to get this to work.

您将需要使用POST或GET方法使用脚本语言。如果你有一个答案和工作方案,请让我知道!我尽我所能让这一切正常运转。

#4


-1  

I recommend using another service for AJAX analytics: http://discrete.li/

我建议使用另一个服务进行AJAX分析:http://discrete te.li/

It automatically gives you stats on all ajax requests, much like google analytics automatically gives you page stats. No need to manually call the service on each success function. Plus, it gives you informations on errors, latency, and full payload logs.

它自动提供所有ajax请求的统计信息,就像谷歌分析自动提供页面统计信息一样。无需手动调用每个成功函数上的服务。此外,它还提供关于错误、延迟和完整有效负载日志的信息。