大网数据广告活动
Web 标准与前端开发

unload

· 52CE 我爱测

1. beforeunload (可取消默认行为的事件) 2. pagehide

当文档或一个子资源正在被卸载时,触发 unload 事件。

<table class="properties"> <tbody> <tr> <th scope="row">可冒泡(Bubbles)</th> <td>No</td> </tr> <tr> <th scope="row">可取消(Cancelable)</th> <td>No</td> </tr> <tr> <th scope="row">接口(Interface)</th> <td>Event</td> </tr> <tr> <th scope="row">事件处理程序属性(Event handler property)</th> <td> WindowEventHandlers/onunload </td> </tr> </tbody> </table>

它在下面两个事件后被触发:

  1. beforeunload (可取消默认行为的事件)
  2. pagehide

文档处于以下状态:

  • 所有资源仍存在 (图片,iframe 等.)
  • 对于终端用户所有资源均不可见
  • 界面交互无效 (window.open, alert, confirm 等.)
  • 错误不会停止卸载文档的过程

请注意unload事件也遵循文档树:父 iframe 会在子 iframe 卸载前卸载 (参考下面的例子).

示例

<!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() 消息描述的顺序触发。

规范

浏览器兼容性

参见

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。