Window: error event - Web APIs 编辑
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.
Bubbles | No |
---|---|
Cancelable | No |
Interface | Event or UIEvent |
Event handler property | onerror |
The event object is a UIEvent
instance if it was generated from a user interface element, or an Event
instance otherwise.
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>Event log:</label>
<textarea readonly class="event-log-contents" rows="8" cols="30"></textarea>
</div>
CSS
body {
display: grid;
grid-template-areas: "control log";
}
.controls {
grid-area: control;
display: flex;
align-items: center;
justify-content: center;
}
.event-log {
grid-area: log;
}
.event-log-contents {
resize: none;
}
label, button {
display: block;
}
button {
height: 2rem;
margin: .5rem;
}
img {
width: 0;
height: 0;
}
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 | Status |
---|---|
UI Events | Working Draft |
Browser compatibility
BCD tables only load in the browser
See also
- This event on
Element
targets:error
event
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论