Join MDN and developers like you at Mozilla's View Source conference, November 2-4 in Portland, Oregon. Learn more at https://viewsourceconf.org/.

An event handler for the error event. Error events are fired at various targets for different kinds of errors:

  • When a JavaScript runtime error (including syntax errors) occurs, an error event using interface ErrorEvent is fired at window and window.onerror() is invoked.
  • When a resource (such as an <img> or <script>) fails to load, an error event using interface Event is fired at the element, that initiated the load, and the onerror() handler on the element is invoked.

The latter error events do not bubble up to window, but (at least in Firefox) can be handled with a single capturing window.addEventListener.

Syntax

For historical reasons, different arguments are passed to window.onerror and element.onerror handlers.

window.onerror

window.onerror = funcRef;

funcRef is a reference to a function. When the function returns true, this prevents the firing of the default event handler. Function parameters:

  • Error message (string)
  • URL of the script where the error was raised (string)
  • Line number where error was raised (number)
  • Column number for the line where the error occurred (number)
  • Error Object (object)

element.onerror

element.onerror accepts a function with a single argument of type Event.

Notes

When a syntax(?) error occurs in a script, loaded from a different origin, the details of the syntax error are not reported to prevent leaking information (see bug 363897). Instead the error reported is simply "Script error." This behavior can be overriden in some browsers using the crossorigin attribute on <script> and having the server send the appropriate CORS HTTP response headers.

When using the inline html markup (<body onerror="alert('an error occurred')>...), the arguments are not named. They can be referenced by arguments[0] through arguments[2].

Specifications

Specification Status Comment
WHATWG HTML Living Standard
The definition of 'onerror' in that specification.
Living Standard  

Browser compatibility

Before Firefox 14 when a <script> failed to load, window.onerror was invoked with message "Error loading script". This was fixed in bug 737087, now scriptElement.onerror is invoked instead in such cases.

Since Firefox 31 you can access the stack trace of a script error from window.onerror via the provided Error object (bug 355430.)

Document Tags and Contributors

Last updated by: cvrebert,
Hide Sidebar