Window: error event

The error event is fired on a Window object when a resource failed to load or couldn't be used — for example if a script has an execution error.

This event is not cancelable and does not bubble.

Syntax

Use the event name in methods like addEventListener(), or set an event handler property.

addEventListener('error', (event) => {});

onerror = (event) => { };

Event type

The event object is a UIEvent instance if it was generated from a user interface element, or an Event instance otherwise.

Event UIEvent

Examples

Live example

HTML

<div class="controls">
  <button id="script-error" type="button">Generate script error</button>
  <img class="bad-img" />
</div>

<div class="event-log">
  <label for="eventLog">Event log:</label>
  <textarea readonly class="event-log-contents" rows="8" cols="30" id="eventLog"></textarea>
</div>

JS

const log = document.querySelector('.event-log-contents');

window.addEventListener('error', (event) => {
    log.textContent = `${log.textContent}${event.type}: ${event.message}\n`;
    console.log(event)
});

const scriptError = document.querySelector('#script-error');
scriptError.addEventListener('click', () => {
    const badCode = 'const s;';
    eval(badCode);
});

Result

Specifications

Specification
HTML Standard
# event-error
HTML Standard
# handler-onerror

Browser compatibility

BCD tables only load in the browser

See also

  • This event on Element targets: error event