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 .

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.


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.
  // Chrome requires returnValue to be set.
  event.returnValue = '';