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 ?

Using beforeunload Event

In this example, we will have a form with multiple input elements and we will add a "beforeunload" event listener on the window object to detect if the user is leaving the page. Inside the event listener callback, we will check whether the user has any unsaved changes in the form. If changes are detected, we will show a prompt with a warning message.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Warning Before Leaving Page with Unsaved Changes</title>
   <style>
      #myForm {
         display: flex;
         flex-direction: column;
         width: 300px;
         gap: 10px;
         margin: 20px;
      }
      #refresh {
         width: 150px;
         margin: 20px;
         padding: 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="email" 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');

      // Store initial form state
      const initialFormState = {
         name: name.value,
         email: email.value,
         subject: subject.value
      };

      let formSaved = false;

      // Handle form submission
      submitBtn.addEventListener('click', e => {
         e.preventDefault();
         formSaved = true;
         alert('Form submitted successfully!');
      });

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

      // Check for unsaved changes before leaving
      window.addEventListener('beforeunload', e => {
         if (formSaved) return; // Don't show warning if form is saved

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

         // Compare current state with initial state
         if (JSON.stringify(initialFormState) !== JSON.stringify(currentFormState)) {
            e.preventDefault();
            e.returnValue = ''; // Modern browsers show generic message
         }
      });
   </script>
</body>
</html>

Alternative Methods Comparison

There are different events we can use to handle page unloading. Here's how they differ:

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Different Unload Events Comparison</title>
</head>
<body>
   <h2>Try closing this tab or navigating away</h2>
   <p>Check the browser console for event logs</p>

   <script>
      // Method 1: beforeunload (recommended for warnings)
      window.addEventListener('beforeunload', function(e) {
         console.log('beforeunload: User is about to leave');
         e.preventDefault();
         e.returnValue = ''; // Shows browser's default warning
      });

      // Method 2: pagehide (mobile-friendly)
      window.addEventListener('pagehide', function(e) {
         console.log('pagehide: Page is being hidden');
         // Cannot show confirmation dialog here
      });

      // Method 3: unload (legacy, limited functionality)
      window.addEventListener('unload', function(e) {
         console.log('unload: Page is being unloaded');
         // Cannot show confirmation dialog here
      });
   </script>
</body>
</html>

Event Comparison Table

Event Can Show Warning? Mobile Support Best Use Case
beforeunload Yes Limited Warning dialogs
pagehide No Excellent Cleanup tasks
unload No Poor Legacy support only

Key Points

  • Modern browsers show generic warning messages instead of custom text for security reasons
  • Mobile browsers may not support beforeunload warnings
  • Form state tracking is essential to determine when to show warnings
  • User actions like form submission should disable warnings to avoid false alerts

Browser Compatibility

The beforeunload event is well-supported across modern browsers, but behavior may vary on mobile devices. Always test your implementation across target browsers and devices.

Conclusion

Implementing a warning message before leaving a web page with unsaved changes using JavaScript's beforeunload event is crucial for preventing accidental data loss. Track form state changes and only show warnings when necessary to provide the best user experience.

Updated on: 2026-03-15T23:19:01+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements