onbeforeunload 特性为 WindowEventHandlers 混合 EventHandler 为处理 beforeunload events. These events fire when a window is about to unload its resources. At this point, the document is still visible and the event is still cancelable.

注意: To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with. Moreover, some don't display them at all.

句法

window.addEventListener("beforeunload", function(event) { ... });
window.onbeforeunload = function(event) { ... };
					

Typically, it is better to use window.addEventListener() beforeunload event, instead of onbeforeunload .

范例

This example prompts the user before unloading.

The HTML specification states that authors should use the Event.preventDefault() method instead of using Event.returnValue to prompt the user.

window.addEventListener('beforeunload', function (e) {
  // Cancel the event
  e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
  // Chrome requires returnValue to be set
  e.returnValue = '';
});
					

Guarantee the browser unload by removing the returnValue property of the event

window.addEventListener('beforeunload', function (e) {
  // the absence of a returnValue property on the event will guarantee the browser unload happens
  delete e['returnValue'];
});
					

注意事项

When your page uses JavaScript to render content, the JavaScript may stop when leaving and then navigating back to the page. You can bind to window.onbeforeunload to prevent the browser from fully caching the page. If you do so, JavaScript in the page will be triggered on the subsequent return visit and update the content as desired.

规范

The event was originally introduced by Microsoft in Internet Explorer 4 and standardized in the HTML5 specification.

规范 状态 注释
HTML 实时标准
The definition of 'onbeforeunload' in that specification.
实时标准
HTML 5.1
在该规范中的 GlobalEventHandlers 定义。
推荐
HTML5
在该规范中的 GlobalEventHandlers 定义。
推荐

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
onbeforeunload Chrome 1 Edge 12 Firefox 1 IE 4 Opera 12 Safari 3 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 12 Safari iOS 1 Samsung Internet Android 1.0
Custom text support 弃用 非标 Chrome ? — 51 Edge No Firefox ? — 44 IE Yes Opera ? — 38 Safari ? — 9 WebView Android ? — 51 Chrome Android ? — 51 Firefox Android ? — 44 Opera Android ? — 41 Safari iOS No Samsung Internet Android ? — 5.0

图例

完整支持

完整支持

不支持

不支持

非标。预期跨浏览器支持较差。

非标。预期跨浏览器支持较差。

弃用。不要用于新网站。

弃用。不要用于新网站。

The HTML specification states that authors should use the Event.preventDefault() method instead of using Event.returnValue to prompt the user. However, this is not yet supported by all browsers.

When this event returns (or sets the returnValue property to) a value other than null or undefined , the user will be prompted to confirm the page unload. In older browsers, the return value of the event is displayed in this dialog. Starting with Firefox 44, Chrome 51, Opera 38, and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example:

  • Firefox displays the string, "This page is asking you to confirm that you want to leave - data you have entered may not be saved." (see bug 588292 ).
  • Chrome displays the string, "Do you want to leave this site? Changes you made may not be saved." (see Chrome Platform Status ).

Internet Explorer does not respect the null return value and will display this to users as "null" text. You have to use undefined to skip the prompt.

In some browsers, calls to window.alert() , window.confirm() ,和 window.prompt() may be ignored during this event. See the HTML specification 了解更多细节。

Note also, that various browsers ignore the result of the event and do not ask the user for confirmation at all. In such cases, the document will always be unloaded automatically. Firefox has a switch named dom.disable_beforeunload in about:config to enable this behaviour. As of Chrome 60, the confirmation will be skipped if the user has not performed a gesture in the frame or page since it was loaded. Pressing F5 in the page seems to count as user interaction, whereas mouse-clicking the refresh arrow or pressing F5 with Chrome DevTools focused does not count as user interaction (as of Chrome 81).

元数据

  • 最后修改:
  1. WindowEventHandlers
  2. 特性
    1. onafterprint
    2. onbeforeprint
    3. onbeforeunload
    4. onhashchange
    5. onlanguagechange
    6. onmessage
    7. onmessageerror
    8. onpopstate
    9. onrejectionhandled
    10. onstorage
    11. onunhandledrejection
    12. onunload
  3. 实现通过:
    1. HTMLBodyElement
    2. HTMLFrameSetElement
    3. Window
  4. HTML DOM 相关页面
    1. BeforeUnloadEvent
    2. DOMStringMap
    3. ErrorEvent
    4. GlobalEventHandlers
    5. HTMLAnchorElement
    6. HTMLAreaElement
    7. HTMLAudioElement
    8. HTMLBRElement
    9. HTMLBaseElement
    10. HTMLBaseFontElement
    11. HTMLBodyElement
    12. HTMLButtonElement
    13. HTMLCanvasElement
    14. HTMLContentElement
    15. HTMLDListElement
    16. HTMLDataElement
    17. HTMLDataListElement
    18. HTMLDialogElement
    19. HTMLDivElement
    20. HTMLDocument
    21. HTMLElement
    22. HTMLEmbedElement
    23. HTMLFieldSetElement
    24. HTMLFormControlsCollection
    25. HTMLFormElement
    26. HTMLFrameSetElement
    27. HTMLHRElement
    28. HTMLHeadElement
    29. HTMLHeadingElement
    30. HTMLHtmlElement
    31. HTMLIFrameElement
    32. HTMLImageElement
    33. HTMLInputElement
    34. HTMLIsIndexElement
    35. HTMLKeygenElement
    36. HTMLLIElement
    37. HTMLLabelElement
    38. HTMLLegendElement
    39. HTMLLinkElement
    40. HTMLMapElement
    41. HTMLMediaElement
    42. HTMLMetaElement
    43. HTMLMeterElement
    44. HTMLModElement
    45. HTMLOListElement
    46. HTMLObjectElement
    47. HTMLOptGroupElement
    48. HTMLOptionElement
    49. HTMLOptionsCollection
    50. HTMLOutputElement
    51. HTMLParagraphElement
    52. HTMLParamElement
    53. HTMLPictureElement
    54. HTMLPreElement
    55. HTMLProgressElement
    56. HTMLQuoteElement
    57. HTMLScriptElement
    58. HTMLSelectElement
    59. HTMLShadowElement
    60. HTMLSourceElement
    61. HTMLSpanElement
    62. HTMLStyleElement
    63. HTMLTableCaptionElement
    64. HTMLTableCellElement
    65. HTMLTableColElement
    66. HTMLTableDataCellElement
    67. HTMLTableElement
    68. HTMLTableHeaderCellElement
    69. HTMLTableRowElement
    70. HTMLTableSectionElement
    71. HTMLTemplateElement
    72. HTMLTextAreaElement
    73. HTMLTimeElement
    74. HTMLTitleElement
    75. HTMLTrackElement
    76. HTMLUListElement
    77. HTMLUnknownElement
    78. HTMLVideoElement
    79. HashChangeEvent
    80. 历史
    81. ImageData
    82. 定位
    83. MessageChannel
    84. MessageEvent
    85. MessagePort
    86. Navigator
    87. NavigatorGeolocation
    88. NavigatorID
    89. NavigatorLanguage
    90. NavigatorOnLine
    91. NavigatorPlugins
    92. PageTransitionEvent
    93. Plugin
    94. PluginArray
    95. PopStateEvent
    96. PortCollection
    97. PromiseRejectionEvent
    98. RadioNodeList
    99. Transferable
    100. ValidityState
    101. Window
    102. WindowBase64
    103. WindowTimers