我正在尝试在用户注册之后和他被重定向之前向 Google Analytics 发送一个事件。 我正在使用 Google 跟踪代码管理器和通用 js。
首先,我尝试使用 dataLayer 对象,如下所述:developers.google
这是我的函数的样子:
//Registering new user via ajax
$.ajax('/register/', {
success: function() {
//Pushing event to dataLayer
dataLayer.push({
'Category': 'Registration Process',
'event': 'Registration Submit Btn'
});
//Logging in new user and redirecting the page with a timeout
setTimeout(function(){
loginAction();
}, 500)
}
})
问题是我只收到了所有事件的大约 25%,所有其他的都丢失了。我不知道在将对象添加到 dataLayer 之后是否以及何时将事件实际发送到 Google,我认为 75% 的事件根本没有发送。
现在我正在尝试实现另一种方法:
//Registering new user via ajax
$.ajax('/register/', {
success: function() {
//Sending event through ga('send')
parent.ga('send', 'event', 'Registration Process', 'Registration Submit Btn');
//Logging in new user and redirecting the page with a timeout
setTimeout(function(){
loginAction();
}, 500)
}
})
但是ga('send')
又没有任何回调函数了!
如何使用 dataLayer 或 ga('send') 确保事件确实发送给了 Google?
最佳答案
终于明白了。它非常复杂,文档中没有描述。 就我而言,我使用的是 Google 跟踪代码管理器,因此我必须采取一些解决方法才能成功触发事件并获得回调。
首先,我们必须得到 ClientId ,这是发送到 Google 服务器的任何事件所必需的。实际上它保存在 cookie 中,但 Google 不建议直接从那里获取它。
这是 Google 推荐的获取方式,但如果您使用的是 Google 跟踪代码管理器,这将不起作用。
ga(function(tracker) {
var clientId = tracker.get('clientId');
});
相反,您必须从 getAll 方法获取 ClientId。
var clientId = ga.getAll()[0].get('clientId');
之后,您必须创建新的跟踪器
ga('create', 'UA-XXX-YYY', {
'clientId': clientId
});
然后我们可以发送一个事件:
ga('send', 'event', {
'eventCategory': 'YOUR Category Name', //required
'eventAction': 'YOUR Action name', //required
'eventLabel': 'YOUR Label',
'eventValue': 1,
'hitCallback': function() {
console.log('Sent!!');
//callback function
},
'hitCallbackFail' : function () {
console.log("Unable to send Google Analytics data");
//callback function
}
});
关于javascript - Google Analytics 发送事件回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23760595/