问题
I added a JavaScript Error trigger in GTM, and obviously it won't fired in the page before gtm loads. I wonder how can I catch those errors, e.g. I have below script before gtm loads
<script>
undefinedObject.undefinedMethod();
</script>
// I can see error in browser console but GTM because this error occurs before GTM loads.
I tried to overwrite window.onerror
function at the very beginning with pushing error event to dataLayer
window.dataLayer = window.dataLayer || [];
window.onerror = function (msg, url, lineNo, columnNo, error) {
var event = {
'event': "gtm.pageError",
'gtm.errorLineNumber': lineNo,
'gtm.errorMessage': msg,
'gtm.errorUrl': url,
'gtm.uniqueEventId': dataLayer.length+1
}
dataLayer.push(event);
return false;
}
It does capture the error as the event is already in dataLayer
when gtm initialize, but then after gtm loaded, any errors come later will be pushed to dataLayer
TWICE as I overwrite the default window.onerror
and gtm overwrite again when it loads
// window.onerror definition in GTM source file
ƒ (d,e,f,h,k){
c&&c(d,e,f,h,k); // this should be running the default `window.onerror` which I edited previously
Um({ // then GTM do it again
event:"gtm.pageError",
"gtm.errorMessage":d,
"gtm.errorUrl":e,
"gtm.errorLineNumber":f
});
return!1
}
So, what is the correct way to capture JS Error with GTM? without logging every errors twice or be able to capture error before gtm loads. Thank you so much.
来源:https://stackoverflow.com/questions/64585248/google-tag-manager-javascript-error-trigger-not-fired-before-gtm-load