BeforeUnloadEvent

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

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

Bubbles No
Cancelable Yes
Target objects defaultView
Interface Event

示例

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

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

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

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

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

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
BeforeUnloadEventChrome Full support YesEdge Full support 12Firefox Full support 1.5IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
User interaction required for dialog boxChrome Full support 60Edge Full support ≤79Firefox ? IE ? Opera Full support 47Safari ? WebView Android Full support 60Chrome Android Full support 60Firefox Android ? Opera Android Full support 44Safari iOS ? Samsung Internet Android Full support 8.0

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown

参见