Add confirm box before user leave your page

June 6, 2020

Before closing any tab, the beforeunload event will be triggered by the browser. The beforeunload event is triggered 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.

To show a confirmation dialog before unloading, you need to call event.preventDefault(). In addition to that, some browser requires one of the below action

  • assigning a string to the event's returnValue property
  • returning a string from the event handler

Example (assigning a string to the event's returnValue property)

window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Some browser requires returnValue to be set.
  event.returnValue = '';

});

Example (returning a string from the event handler)

window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Some browser requires returning a string
  return "";
});

calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.