[英]Why Isn't Google Analytics Event Firing/Saving?
I've got a google analytics tracker loaded into an iFrame: 我已经将Google Analytics(分析)跟踪器加载到iFrame中:
(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-my-id-here');
ga('set', 'location', 'http://foo.com/bar');
ga('set', 'title', 'Awesome');
ga('send', 'pageview');
I've also got custom Javascript trying to track events in a rich-client application on the same page, which has a reference to the ga instance above, and tries to send an event: 我也有自定义Javascript试图跟踪同一页面上富客户端应用程序中的事件,该应用程序引用了上面的ga实例,并尝试发送事件:
ga('send', 'event', 'my_category', 'my_event', 'my_value');
When I load the page I see the initial pageview tracked properly. 加载页面时,我看到初始浏览量已正确跟踪。 When I click and fire off the custom event tracking, the JavaScript executes and does not throw an error. 当我单击并启动自定义事件跟踪时,JavaScript将执行并且不会引发错误。 It also does not register any event. 它还不注册任何事件。
确保您要在网页摘要之后尝试调用的页面已加载analytics.js(如果位于iframe中)
ga('send', 'event', 'my_category', 'my_event', 'my_value');
The problem ended up being an issue of JavaScript scoping. 该问题最终成为JavaScript作用域的问题。
The analytics.js
application only works when all calls are appropriately within the same Javascript scope. 仅当所有调用都在同一Javascript范围内适当时, analytics.js
应用程序才能工作。 I was trying to fire a GA event within a different page scope (due to an embedded JS app and iFrames, it's complicated). 我试图在其他页面范围内触发GA事件(由于嵌入式JS应用和iFrame,这很复杂)。
The solution was the following: 解决方案如下:
<script type="text/javascript">
(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-my-id');
ga('set', 'hostname', 'awesome.com');
ga('set', 'location', '/path/to/awesome');
ga('set', 'referrer', 'REFERRER_VALUE');
ga('set', 'title', 'Awesome App');
ga('send', 'pageview');
window.trackGAEvent = function(eventName, value) {
ga('send', 'event', 'awesome_app', eventName, value);
}
</script>
The trick was encapsulating the ga
event send
call. 诀窍是封装ga
事件send
调用。 I can call this method from other contexts by drilling down the DOM, but I can't call the GA app directly from outside the proper context. 我可以通过深入研究DOM在其他上下文中调用此方法,但不能在适当的上下文外部直接调用GA应用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.