Window: beforeunload event

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

Browser compatibility

BCD tables only load in the browser

See WindowEventHandlers/onbeforeunload for more details on how various browsers handle this event.

See also