How to display a warning before leaving the web page with unsaved changes using JavaScript?


In this article, we will learn how to display a warning message before leaving the web page with unsaved changes using javascript with the help of the “beforeunload” event listener.

When working on web applications or forms of any kind, it becomes necessary to provide a warning message to users before they leave a page with unsaved changes. This can prevent accidental data loss and improve the overall user experience. Let’s understand how we can implement this with the help of some examples −

Example 1

In this example, we will have a form with multiple input elements and we will add a “beforeunload” event listener here on the window object to detect if the user is leaving the page. Inside the event listener callback, we will have a check to determine whether the user has any saved changes in the form. If it does, we will show a prompt with a generic message of unsaved changes being present on the page, else the user will continue to leave the page.

Filename: index.html

<html lang="en">
   <head>
      <title>How to display warning before leaving the web page with unsaved changes using JavaScript?</title>

      <style>
      #myForm {
         display: flex;
         flex-direction: column;
         width: 300px;
         gap: 10px;
      }
      </style>
   </head>
   <body>
      <form id="myForm">
         <label for="name">Name:</label>
         <input type="text" id="name" name="name" />
         <label for="email">Email:</label>
         <input type="text" id="email" name="email" />
         <label for="subject">Subject:</label>
         <input type="text" id="subject" name="subject" />
         <input type="submit" value="Submit" />
      </form>

   <button id="refresh">Refresh the page!</button>

   <script>
      const form = document.getElementById('myForm');
      const name = document.getElementById('name');
      const email = document.getElementById('email');
      const subject = document.getElementById('subject');
      const submitBtn = document.querySelector('input[type="submit"]');
      const refreshBtn = document.getElementById('refresh');

      refreshBtn.addEventListener('click', e => {
         e.preventDefault();
         window.location.reload();
      })

      const initialFormState = {
         name: name.value,
         email: email.value,
         subject: subject.value
      };

      submitBtn.addEventListener('click', e => {
         e.preventDefault();
      })

      window.addEventListener('beforeunload', e => {
         const currentFormState = {
            name: name.value,
            email: email.value,
            subject: subject.value
         }

         if (JSON.stringify(initialFormState) !== JSON.stringify(currentFormState)) {
            e.preventDefault();
            e.returnValue = '';
         }
      })
   </script>
   </body>
</html>

Example 2

In this example, we will follow the above code structure and use 3 different methods to display a warning message before leaving the web page, using onbeforeunload, pagehide, and unload events.

Filename: index.html

<html lang="en">
<head>
   <title>How to display warning before leaving the web page with unsaved changes using JavaScript?</title>

   <style>
      #myForm {
         display: flex;
         flex-direction: column;
         width: 300px;
         gap: 10px;
      }
   </style>
</head>
<body>
   <form id="myForm">
      <label for="name">Name:</label>
      <input type="text" id="name" name="name" />
      <label for="email">Email:</label>
      <input type="text" id="email" name="email" />
      <label for="subject">Subject:</label>
      <input type="text" id="subject" name="subject" />
      <input type="submit" value="Submit" />
   </form>

   <button id="refresh">Refresh the page!</button>

   <script>
      const form = document.getElementById('myForm');
      const name = document.getElementById('name');
      const email = document.getElementById('email');
      const subject = document.getElementById('subject');
      const submitBtn = document.querySelector('input[type="submit"]');
      const refreshBtn = document.getElementById('refresh');

      refreshBtn.addEventListener('click', e => {
         e.preventDefault();
         window.location.reload();
      })

      const initialFormState = {
         name: name.value,
         email: email.value,
         subject: subject.value
      };

      submitBtn.addEventListener('click', e => {
         e.preventDefault();
      })

      // Example 1: Using onbeforeunload Property
      window.onbeforeunload = function() {
         const currentFormState = {
            name: name.value,
            email: email.value,
            subject: subject.value
         };

         if (JSON.stringify(initialFormState) !== JSON.stringify(currentFormState)) {
            return 'You have unsaved changes. Are you sure you want to leave this page?';
         }
      };

      // Example 2: Using pagehide event
         window.addEventListener('pagehide', function(e) {
            const currentFormState = {
            name: name.value,
            email: email.value,
            subject: subject.value
            };

         if (JSON.stringify(initialFormState) !== JSON.stringify(currentFormState)) {
            const confirmationMessage = 'You have unsaved changes. Are you sure you want to leave this page?';
            (e || window.event).returnValue = confirmationMessage;
            return confirmationMessage;
            }
         });

      // Example 3: Using onunload property
      window.onunload = function() {
         const currentFormState = {
            name: name.value,
            email: email.value,
            subject: subject.value
         };

         if (JSON.stringify(initialFormState) !== JSON.stringify(currentFormState)) {
            // Perform any necessary cleanup actions
         }
      };
   </script>
</body>
</html>

Conclusion

In conclusion, implementing a warning message before leaving a web page with unsaved changes using JavaScript is crucial for providing a better user experience and preventing accidental data loss. By following the example HTML structure and JavaScript code provided in this article, we learned how to integrate this functionality into our web applications or forms easily

Updated on: 03-Aug-2023

977 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements