Google Tag Manager JavaScript Error trigger not fired before gtm load

人走茶凉 提交于 2021-01-29 08:08:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!