【问题标题】:Using JS Callback with Google Analytics在 Google Analytics 中使用 JS 回调
【发布时间】:2011-04-05 15:01:16
【问题描述】:

我有一个简单的页面,我需要执行一些 GWO 和 GATC js,然后重定向到另一个 url。

<head>

<script>
function utmx_section(){}function utmx(){}
(function(){var k='xxx',d=document,l=d.location,c=d.cookie;function f(n){
if(c){var i=c.indexOf(n+'=');if(i>-1){var j=c.indexOf(';',i);return escape(c.substring(i+n.
length+1,j<0?c.length:j))}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash;
d.write('<sc'+'ript src="'+
'http'+(l.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com'
+'/siteopt.js?v=1&utmxkey='+k+'&utmx='+(x?x:'')+'&utmxx='+(xx?xx:'')+'&utmxtime='
+new Date().valueOf()+(h?'&utmxhash='+escape(h.substr(1)):'')+
'" type="text/javascript" charset="utf-8"></sc'+'ript>')})();
</script><script>utmx("url",'A/B');</script>

<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['gwo._setAccount', 'UA-xxxxxx-x']);
  _gaq.push(['gwo._trackPageview', '/xxxxxxxx/test']);
  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-    analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>

<script>
    window.location = 'MY REDIRECT URL';
</script>
</head>

我遇到的问题是我需要保证在调用 window.location 之前执行 GWO 和 GATC 代码。我可以做 setTimeout,但这不能保证并增加额外的加载时间。

关于如何做到这一点的任何想法?

【问题讨论】:

    标签: javascript callback google-analytics google-website-optimizer


    【解决方案1】:

    我相信我已经找到了解决方案。事实证明,您可以将函数推送到 _gaq。然后按顺序执行 _gaq,确保在到达我的重定向之前处理好 GA 内容。

     var _gaq = _gaq || [];
      _gaq.push(['gwo._setAccount', 'UA-xxxxxx-x']);
      _gaq.push(['gwo._trackPageview', '/xxxxxxxx/test']);
    
      _gaq.push(function(){
        window.location = 'MY REDIRECT URL';
      });
    

    http://code.google.com/apis/analytics/docs/tracking/asyncUsageGuide.html#PushingFunctions

    【讨论】:

    • 这可行且有意义,但出于某种原因,official suggestion 是在将事件推送到 GA 队列后几毫秒使用 setTimeout 重定向。
    • @lucasrizoli 和所有我认为一旦 GA 代码发出对像素的请求但不会在返回后调用该函数。也许这就是谷歌建议延迟重定向的原因,尽管我不知道等待请求返回是否重要。
    • 虽然从队列中按顺序处理,但没有说在下一个指令被触发之前之前的指令已经完成处理 => 仍然需要超时。然而,谷歌正在倾听这样的要求,请继续关注 ga.js 更新日志code.google.com/intl/fr/apis/analytics/community/…
    【解决方案2】:

    _gaq.push 对我不起作用...

    我使用了已知的 setTimeout 解决方案:

    $('.link-site').click(function(e){
        e.preventDefault();
        _gaq.push(['_trackPageview', '/btn-link-site']);
        window.setTimeout(function(){
            window.location=$('.link-site').attr('href');
        },300);
    });
    

    【讨论】:

    • 这比公认的解决方案要好,因为推送到异步队列的命令是异步发生的 :) 这可能不会 100% 起作用,但它比不暂停更有可能成功全部。
    • 这是一个 hack,而不是一个合适的解决方案。不保证事件将在重定向之前执行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多