Window: beforeunload event - Web APIs 编辑
The beforeunload
event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.
Bubbles | No |
---|---|
Cancelable | Yes |
Interface | Event |
Event handler property | onbeforeunload |
This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser navigates to the new page, otherwise it cancels the navigation.
According to the specification, to show the confirmation dialog an event handler should call preventDefault()
on the event.
However note that not all browsers support this method, and some instead require the event handler to implement one of two legacy methods:
- assigning a string to the event's
returnValue
property - returning a string from the event handler.
Some browsers used to display the returned string in the confirmation dialog, enabling the event handler to display a custom message to the user. However, this is deprecated and no longer supported in most browsers.
To combat unwanted pop-ups, browsers may not display prompts created in beforeunload
event handlers unless the page has been interacted with, or may even not display them at all.
Attaching an event handler/listener to window
or document
's beforeunload
event prevents browsers from using in-memory page navigation caches, like Firefox's Back-Forward cache or WebKit's Page Cache.
The HTML specification states that calls to window.alert()
, window.confirm()
, and window.prompt()
methods may be ignored during this event. See the HTML specification for more details.
Note: You shouldn't use the beforeunload
event with sendBeacon()
. See the Navigator.sendBeacon()
page for more details and best practices.
Examples
The HTML specification states that authors should use the Event.preventDefault()
method instead of using Event.returnValue
. However, this is not supported by all browsers.
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Older browsers supported custom message
event.returnValue = '';
});
Specifications
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'beforeunload' in that specification. | Living Standard | |
HTML5 The definition of 'beforeunload' in that specification. | Recommendation | Initial definition |
Browser compatibility
BCD tables only load in the browser
See WindowEventHandlers/onbeforeunload for more details on how various browsers handle this event.
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论