Categories
JavaScript Answers

How to show the “Are you sure you want to navigate away from this page?” message when changes committed with JavaScript?

Spread the love

To show the "Are you sure you want to navigate away from this page?" message when changes committed with JavaScript, we set the window.onbeforeunload property to a function that returns a truthy value.

For instance, we write

window.onbeforeunload = () => {
  return true;
};

to set window.onbeforeunload to a function that returns true to show the "Are you sure you want to navigate away from this page?" message before the tab or window is closed or navigation starts.

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 *