Categories
JavaScript Answers

How to Warn User Before Leaving a Web Page with Unsaved Changes?

Spread the love

Sometimes, we need to warn users before leaving a web page when there’re unsaved changes in a form.

This way, the user won’t lose the form data when they leave a web page accidentally.

In this article, we’ll look at how to add a warning for the user before leaving a web page when there’re unsaved changes in a form.

Listen to the beforeunload Event

We can listen to the beforeunload event which is emitted when we leave a page.

And in the event handler, we can check if the form values have been changed and act accordingly.

For instance, we can write the following HTML to create a form:

<form>
  <input type='text'>
  <input type="submit" />
</form>

Then we can write the following JavaScript:

let isDirty = false
const input = document.querySelector('input[type="text"]')
input.addEventListener('change', () => {
  isDirty = true
})

window.addEventListener("beforeunload", (e) => {
  if (!isDirty) {
    return;
  }
  e.returnValue = true;
  return true
});

to check if the text input has been changed.

If it’s been changed, we set isDirty to true .

To determine this, we listen to the change event listener.

If it’s triggered, that means the input has been changed.

Next, we add the event listener for the beforeunload event.

In the event listener, we check if isDirty is true .

If it’s not, we use return to stop running the function.

Otherwise, we set e.returnValue to true to trigger the confirmation dialog to show.

We can’t change the content of that in modern browsers.

This works for more browsers.

Some browsers also trigger the dialog box by returning a truthy value.

Conclusion

We can listen to the beforeunload event to add a warning for the user when they leave a page with a form with unsaved changes.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *