Window: error event

当资源加载失败或无法使用时,会在Window对象触发error事件。例如:script 执行时报错。

Bubbles(支持冒泡) No
Cancelable(可撤销) No
Interface(接口) Event or UIEvent
Event handler property(事件处理程序属性) onerror

如果它是由用户界面元素生成的,或者是由事件实例生成的,那么此事件是UIEvent实例。

示例

在线示例

HTML

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

<div class="event-log">
  <label>Event log:</label>
  <textarea readonly class="event-log-contents" rows="8" cols="30"></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);
});

结果

规范

Specification Status
UI Events Working Draft

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
error eventChrome Full support YesEdge ? Firefox Full support YesIE ? Opera ? Safari ? WebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android ? Safari iOS ? Samsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown

相关事件

  • This event on Element targets: error event