Window: unload event - Web APIs 编辑
The unload
event is fired when the document or a child resource is being unloaded.
Bubbles | No |
---|---|
Cancelable | No |
Interface | Event |
Event handler property | onunload |
It is fired after:
beforeunload
(cancelable event)pagehide
The document is in the following state:
- All the resources still exist (img, iframe etc.)
- Nothing is visible anymore to the end user
- UI interactions are ineffective (
window.open
,alert
,confirm
, etc.) - An error won't stop the unloading workflow
Please note that the unload event also follows the document tree: parent frame unload will happen before child frame unload
(see example below).
The unload
event (and onunload
event handler) are not the right features to use with sendBeacon
. Instead for sendBeacon,
use the visibilitychange
and pagehide
events. See discussion in the comments for the blog post Beacon API is broken.
Examples
<!DOCTYPE html>
<html>
<head>
<title>Parent Frame</title>
<script>
window.addEventListener('beforeunload', function(event) {
console.log('I am the 1st one.');
});
window.addEventListener('unload', function(event) {
console.log('I am the 3rd one.');
});
</script>
</head>
<body>
<iframe src="child-frame.html"></iframe>
</body>
</html>
Below, the content of child-frame.html
:
<!DOCTYPE html>
<html>
<head>
<title>Child Frame</title>
<script>
window.addEventListener('beforeunload', function(event) {
console.log('I am the 2nd one.');
});
window.addEventListener('unload', function(event) {
console.log('I am the 4th and last one…');
});
</script>
</head>
<body>
☻
</body>
</html>
When the parent frame is unloaded, events will be fired in the order described by the console.log()
messages.
Specifications
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'unload' in that specification. | Living Standard |
Browser compatibility
BCD tables only load in the browser
See also
- Related events:
DOMContentLoaded
,readystatechange
,load
- Unloading Documents — unload a document
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论