BeforeUnloadEvent

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

beforeunload 事件触发于 window、document 和它们的资源即将卸载时。

当事件属性 returnValue 被赋值为非空字符串时,会弹出一个对话框,让用户确认是否离开页面(示例如下)。否则,事件被静默处理。一些浏览器实现仅在框架或内置框架接收到用户手势或交互时才显示对话框。在 浏览器兼容性 中查看更多信息。

Bubbles No
Cancelable Yes
Target objects defaultView
Interface Event

示例

js
window.addEventListener("beforeunload", function (event) {
  event.returnValue = "\\o/";
});

//等同于
window.addEventListener("beforeunload", function (event) {
  event.preventDefault();
});

基于 Webkit 的浏览器没有遵循该弹窗规范。以下是一个基本跨浏览器运行的例子。

js
window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\\o/";

  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage; //Webkit, Safari, Chrome etc.
});

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
BeforeUnloadEvent
returnValue
Deprecated
User interaction required for dialog box

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
No support
No support
Deprecated. Not for use in new websites.
Has more compatibility info.

参见