Search code examples
javascriptevent-handlingonerror

Injected JS assigning window.onerror fails to fire


I need to run third party JS to scan jserrors. I am running the following in chrome's console

window.onerror = function(errorMsg, url, lineNumber) {
  alert(errorMsg);
}

throw new Error('foo');

I expect both the console to inform me of the error and a alert to pop up displaying the error message. The alert is never fired, and I assume the event is not being fired. why not?


Solution

  • The Chrome Developer Console won't call the user-defined error event listener if the error is thrown immediately (according to this answer by Paul S.).

    Throwing the error "just in time":

    > window.onerror = function () {console.log('error!');};
    function () {console.log('error!');}
    > throw new Error();
    Error
    

    Throwing the error deferred:

    > window.setTimeout(function() {throw new Error()}, 0);
    xxxx
    error!
    Uncaught Error
    

    (xxxx is the specific return value of setTimeout())


    Here is the original code snippet which led me to the point that the Chrome Dev Console changes the internal behaviour somehow:

    // #btn is a simple button
    document.getElementById("btn").addEventListener("click", function () {
        var script = document.createElement("script");
        script.innerHTML = "window.onerror=function(){alert('An error occurred!');};throw new Error('42');";
        document.head.appendChild(script);
    });
    

    This code is to be executed in a normal HTML file.