[英]Google Analytics dataLayer.push not working in a Javascript Promise
I am running into a weird issue trying to trigger the window.dataLayer.push()
when trying to utilize Google Analytics Tag Manager dataLayer
firing logic when that call is placed inside a Promise
.我遇到了一个奇怪的问题,试图触发window.dataLayer.push()
当该调用放置在Promise
中时尝试利用 Google Analytics 跟踪代码管理器dataLayer
触发逻辑。 I assume this is Promise
based due to the below logic:由于以下逻辑,我假设这是基于Promise
的:
Simply placing this snippet in a.js file loaded in the footer of the site, this works fine and I see it firing in my console:只需将此代码段放在网站页脚中加载的 a.js 文件中,这工作正常,我看到它在我的控制台中触发:
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'dataLayer-initialized',
'pageName': 'First'
});
I then update the file with the following:然后,我使用以下内容更新文件:
const result = callGenericBackend().then((res)=>{return res});
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'dataLayer-initialized',
'pageName': 'First'
});
result.then((res)=>{
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'dataLayer-initialized',
'pageName': 'Second'
});
})
function callGenericBackend(pageID) {
return new Promise((resolve,reject)=>{
jQuery.ajax({
type:'post',
async: true,
url:myAjax.ajaxurl,
data : {pageID: pageID},
dataType: 'json',
error:(xhr)=>{
console.warn('ajax error');
reject(xhr);
return false;
},
success:(data)=>{
if (data.status === 200) {
resolve(data);
} else {
reject(data);
}
}
})
})
The "First" continues to fire, but the "Second" is never fired. “第一”继续开火,但“第二”从未开火。 My callGenericBackend()
simply returns a response via an .ajax
call.我的callGenericBackend()
只是通过.ajax
调用返回响应。 What am I missing here with Promise
logic to make this work?我在这里用Promise
逻辑使这项工作缺少什么? If I change async: false
in callGenericBackend()
it works, but I see this error in my console:如果我在callGenericBackend()
中更改async: false
它可以工作,但我在控制台中看到此错误:
Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
Not sure if this would help since I don't know what data are u getting from the request and what do you want to do with that data:不确定这是否会有所帮助,因为我不知道您从请求中获得了什么数据以及您想对这些数据做什么:
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'dataLayer-initialized',
'pageName': 'First'
});
function callGenericBackend(pageID) {
return $.ajax({
type:'post',
async: true,
url:myAjax.ajaxurl,
data : {pageID: pageID},
dataType: 'json',
error:(xhr)=>{
console.warn('ajax error');
reject(xhr);
return false;
},
success:(data)=>{
if (data.status === 200) {
resolve(data);
} else {
reject(data);
}
}
})
})
}
$.when(callGenericBackend(YOUR_ID)).done(function(response){
//access response data here
window.dataLayer.push({
'event': 'dataLayer-initialized',
'pageName': 'First'
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.