Issue
I know there are many other posts about this topic, but I still can’t get it working.
I am using Angular 8 in my project and I want to send the browser console message to a server log file.
Could someone please clearifiy does questions for me:
- When does the window.onerror get trigged? – right know I put the function within the constructor, is that ok so?
Does it get trigged, if I serve the project local?
window.onerror = function (errorMsg, url, lineNumber) { alert(errorMsg + ' ' + lineNumber); };
- What do I have to do to get it triggered? (or does for example a thrown error of a missing certificate – trigger this function?)
console.error(‘test’) – does this trigger it?
throw new Error() – or this?
- Does Console-Errors like CORS will trigger this function?
- I also read that it would get triggered if an img or script source is not avilable.
app.compentent.html:
<img src="test.png">
app.copmentent.ts in the constructor (the code of point one)
But I still don’t get the alert to display.
I am grateful for any help – thanks
Solution
The following may work for you. I used it in some Vue.js code to test triggering window.onerror(). Using eval() should allow you to bypass the compile-time checks of Angular and putting it in window.onload() will ensure it is evaluated after page load.
window.onerror = function (message, source, lineno, colno, error) {
alert('onerror called: ' + message);
}
window.onload = function () {
eval('undefined_function()');
}
As a security note, don’t use eval() in production, especially if user input could get anywhere near it.