Display Alert before Leaving the Web Page with JavaScript

Web Dev
Sponsored links

In this article, I will introduce how to display alert before leaving the web page with JavaScript.

The beforeunload event

The beforeunload event is an event that occurs when the screen is closed or the web page transitions.
By issuing an alert when the user accidentally tries to close or move on the input screen etc., it is possible to avoid the situation where the input is redone.

Below is the code to display an alert before leaving the web page with the beforeunload event.

 window.addEventListener('beforeunload', (event) => {
  event.preventDefault();
  event.returnValue = '';
});

The event.preventDefault () cancels the event of leaving the web page.

The confirmation dialog behaves slightly differently depending on the browser.
In some browsers such as IE, the character set in event.returnValue is displayed in the confirmation dialog.

In Chrome, the character set in event.returnValue is not displayed, and the browser-specific confirmation dialog is displayed.
However, if the value is not set in event.returnValue, the confirmation dialog will not be displayed, so it is necessary to set an empty string.