How to warn users before leaving a web page with unsaved changes using JavaScript?

Estimated read time 2 min read

To warn users before leaving a web page with unsaved changes using JavaScript, you can add an event listener to the beforeunload event on the window object. The beforeunload event is fired just before the user is about to leave the page, and you can use it to show a confirmation message that gives the user the option to stay on the page and save their changes or leave the page and discard their changes. Here’s an example of how to do this:

window.addEventListener('beforeunload', function(event) {
  if (unsavedChangesExist()) {
    event.preventDefault();
    event.returnValue = '';
  }
});

function unsavedChangesExist() {
  // Check if unsaved changes exist
  // Return true if there are unsaved changes, false otherwise
}

In this code, we add an event listener to the beforeunload event on the window object. Inside the event listener function, we check if there are unsaved changes using a separate function called unsavedChangesExist(). This function should return true if there are unsaved changes and false otherwise.

If unsaved changes exist, we prevent the default behavior of the beforeunload event using the preventDefault() method on the event object. We also set the returnValue property of the event object to an empty string, which shows a confirmation dialog with a default message asking the user if they want to leave the page or stay on the page.

The message shown in the confirmation dialog is controlled by the browser and cannot be customized, but you can add your own message to the returnValue property by setting it to a string. For example, you could set it to 'You have unsaved changes. Are you sure you want to leave?'.

Note that not all browsers support custom messages for the beforeunload event, and some may show a generic message instead. Also note that this event can be used for malicious purposes, so some browsers may display a warning to the user that the page is trying to prevent them from leaving. Therefore, you should use this event with caution and only when necessary.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply