在Google Analytics中使用JS Callback

dor*_*emi 7 javascript google-analytics callback google-website-optimizer

我有一个简单的页面,我需要执行一些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>
Run Code Online (Sandbox Code Playgroud)

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

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

dor*_*emi 26

我相信我找到了解决方案.事实证明,你可以将函数推送到_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';
  });
Run Code Online (Sandbox Code Playgroud)

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

  • 这有效并且有意义,但出于某种原因,[官方建议](http://www.google.com/support/analytics/bin/answer.py?answer=55527)使用`setTimeout`来重定向一些事件被推送到GA队列后的ms. (9认同)
  • 在从队列中按顺序处理时,没有任何内容表示先前的指令将在下一个指令被触发之前完成处理=>仍然需要超时.然而谷歌正在聆听此类需求,敬请关注ga.js更改日志http://code.google.com/intl/fr/apis/analytics/community/gajs_changelog.html (8认同)
  • @lucasrizoli以及所有我认为一旦像素的请求由GA代码发出而不是在它返回之后将调用该函数.也许这就是谷歌建议延迟重定向的原因,虽然我不知道等待请求返回是否重要. (2认同)

小智 6

_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);
});
Run Code Online (Sandbox Code Playgroud)

  • 这比接受的解决方案更好,因为推送到异步队列的命令发生,异步异步:)这可能不会在100%的时间内起作用,但它更有可能成功而不是暂停. (4认同)