当文档或其子资源被卸载时,unload事件会被触发
它在下面两个事件后触发:
- beforeunload (可取消默认行为的事件)
- pagehide
文档会处于一个特殊状态:
- 所有资源仍存在 (图片, iframe 等.)
- 对于终端用户所有资源均不可见
- 界面交互无效 (
window.open
,alert
,confirm
等.) - 错误不会停止卸载文档的过程
请注意unload事件也遵循文档树:父iframe会在子iframe卸载前卸载(参考下面的例子).
通用信息
- 规范
- DOM L3
- 接口
- 若由用户界面触发则为UIEvent接口。否则为Event 接口.
- 是否冒泡
- No
- 能否取消默认行为
- No
- 目标
- defaultView, Document, Element
- 默认行为
- None.
属性
Property | Type | Description |
---|---|---|
target 只读 |
EventTarget |
The event target (the topmost target in the DOM tree). |
type 只读 |
DOMString |
The type of event. |
bubbles 只读 |
Boolean |
Whether the event normally bubbles or not |
cancelable 只读 |
Boolean |
Whether the event is cancellable or not? |
view 只读 |
WindowProxy |
document.defaultView (window of the document) |
detail 只读 |
long (float ) |
0. |
例子
<!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>
下面是 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>
当父iframe被卸载,可以从console.log打印的信息看到unload事件触发的顺序.