Window: unload event - Web APIs 编辑

The unload event is fired when the document or a child resource is being unloaded.

BubblesNo
CancelableNo
InterfaceEvent
Event handler propertyonunload

It is fired after:

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

SpecificationStatusComment
HTML Living Standard
The definition of 'unload' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:114 次

字数:4908

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文