Window: error event
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
当资源加载失败或无法使用时,会在Window
对象触发error
事件。例如:script 执行时报错。
Bubbles(支持冒泡) | No |
---|---|
Cancelable(可撤销) | No |
Interface(接口) | Event or UIEvent |
Event handler property(事件处理程序属性) |
onerror
|
如果它是由用户界面元素生成的,或者是由事件实例生成的,那么此事件是UIEvent
实例。
示例
在线示例
HTML
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
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 |
---|
HTML Standard # event-error |
HTML Standard # handler-onerror |
浏览器兼容性
BCD tables only load in the browser
相关事件
- This event on
Element
targets:error
event