Is assigning a function to window.onerror preferable to window.addEventListener(‘error’, callback)?

For historical reasons these window.onerror is a bit of a special case. Most of these are defunct now, I think you have to back to IE8 to find a browser that needed them. A decade or so ago IE6 was king and it didn’t have support for addEventListener at all, and many events were only supported by some browsers or had different names. Web development used to be wildly inconsistent and it’s not unusual to find old methods like window.onerror.

For backwards compatability reasons window.onerror is a bit weird in that the two ways of subscribing to the event take different arguments.

So the legacy onerror includes error details as parameters:

window.onerror = function(message, source, line, col, error) {
    ...

    return true; // This will prevent further event propagation
};

This is still there so that old JS that’s already out there doesn’t break – browser designers want 10 year old websites to still basically work in their latest versions.

While the (now best practice) event listener has them as properties on the event:

window.addEventListener('error', e => {

    // Get the error properties from the error event object
    const { message, filename, lineno, colno, error } = e; 
});

The latter is far better, as you don’t need to get any previous listeners, and no subsequent listeners (say from browser extensions) will accidentally break yours. Also you can remove your listener if you’re building something like an SPA where you stay on one page with one window context.

So, to answer the question:

Most documentation/blog posts/etc I can find online recommends doing something like this. Why don’t they recommend adding an event handler for the ‘error’ event instead?

Because they’re outdated. Keeping documentation up to date is hard and JS moves fast. The
window.onerror pattern you describe is still an acceptable compromise in some corporate environments where extremely outdated versions of IE need to be supported. For the vast majority of the web the addEventListener method is much better.

see, for example, JQuery’s explicit lack of support for it (search on that page for “onerror”

jQuery is old. There are some decisions that were made in 2006-2008 or so that it’s now stuck with forever, and some assumptions that .on makes about events is one of those. jQuery’s .on was great in 2006 because we didn’t have to worry about different browsers’ event implementations – it could hide all of them behind a common interface. Everything now uses addEventListener so you don’t need it (and it’s a lot more powerful than .on).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)