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.

BubblesNo
CancelableYes
InterfaceEvent
Event handler propertyonbeforeunload

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

SpecificationStatusComment
HTML Living Standard
The definition of 'beforeunload' in that specification.
Living Standard
HTML5
The definition of 'beforeunload' in that specification.
RecommendationInitial 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:152 次

字数:5727

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文