jQuery 如何让 Google Analytics 跟踪 AJAX 调用的页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24199037/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:29:40  来源:igfitidea点击:

How do I get Google Analytics to track pages called by AJAX?

jqueryajaxgoogle-analytics

提问by user2599927

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 调用我网站上的一个页面,但由于某种原因 Google Analytics 没有注册页面访问。我必须做些什么来强制它注册 AJAX 触发的页面吗?

I am using the latest Universal anaytics code as follows:

我正在使用最新的 Universal 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.

我确定正在调用该页面,因为我有一些写入数据库的日志记录语句。我也知道 Analytics 代码正在运行,因为我正在使用实时概览对其进行测试。

So to summarise, I have a page calling http://www.mywebsite.extusing 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) 包含一些 Universal Analytics 代码,这些代码似乎无法跟踪该页面。如果您从浏览器正常访问该页面,则该页面会被很好地跟踪。

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('send', 'pageview');

But I understand there is a minimum interval between events: Google Analytics Event Tracking - Minimal Interval between the 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秒。

回答by GlabbichRulz

The old standardfor loading Google Analytics was the asynchronous method:

加载 Google Analytics的旧标准是异步方法:

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 的历史插件一起使用。

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 Code,虚拟页面加载的语法是不同的。

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/guides/download/seo-beginners-guide.pdf”的虚拟浏览量。

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

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

回答by Ilyas karim

Html

html

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

Javascript

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
        })
    });
});

回答by dav

This answer is for new GA snippets only

此答案仅适用于新的 GA 片段

The upvoted answer did not work for me, here is slightly modified version of this answerthat works for me

该upvoted答案没有工作对我来说,这里略作修改的版本,这个答案是对我的作品

if ("ga" in window) {
    tracker = ga.getAll()[0];
    if (tracker) {
        tracker.set("page", '/some-page');
        tracker.send("pageview");
    }
}

回答by user3313824

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

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

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 方法。如果您提出了答案和可行的解决方案,请告诉我!我正在尽我所能让它发挥作用。