Execute a script when the document is about to be unloaded in HTML?

The onbeforeunload event attribute in HTML fires when the document is about to be unloaded, such as when a user closes the browser tab, navigates away from the page, or refreshes it. This event is commonly used to warn users about unsaved changes or to perform cleanup operations before the page is destroyed.

Syntax

Following is the syntax for the onbeforeunload event attribute −

<element onbeforeunload="script">

The event handler function can return a string message that will be displayed in the browser's confirmation dialog. However, modern browsers may show their own generic message instead of custom text for security reasons.

Using onbeforeunload as HTML Attribute

The onbeforeunload attribute can be added directly to the <body> element to handle the event when the page is about to unload.

Example

Following example demonstrates the basic usage of the onbeforeunload attribute −

<!DOCTYPE html>
<html>
<head>
   <title>onbeforeunload Example</title>
</head>
<body onbeforeunload="return display()" style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Unload Event Demo</h2>
   <p>Try to close this window, refresh the page (F5), or navigate away to trigger the unload warning.</p>
   <script>
      function display() {
         return "Are you sure you want to leave this page?";
      }
   </script>
</body>
</html>

When you attempt to close the tab or navigate away, the browser displays a confirmation dialog asking if you want to leave the page.

Using addEventListener for onbeforeunload

Modern JavaScript applications typically use addEventListener to handle the beforeunload event, providing more flexibility and better separation of concerns.

Example

Following example shows how to use addEventListener for the beforeunload event −

<!DOCTYPE html>
<html>
<head>
   <title>beforeunload with addEventListener</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Form with Unsaved Changes</h2>
   <form>
      <label for="username">Username:</label>
      <input type="text" id="username" name="username"><br><br>
      <label for="email">Email:</label>
      <input type="email" id="email" name="email"><br><br>
      <button type="button" onclick="saveForm()">Save Changes</button>
   </form>
   <p id="status">Form has unsaved changes</p>

   <script>
      let hasUnsavedChanges = true;

      window.addEventListener('beforeunload', function(event) {
         if (hasUnsavedChanges) {
            event.preventDefault();
            event.returnValue = ''; // Chrome requires returnValue to be set
            return 'You have unsaved changes. Are you sure you want to leave?';
         }
      });

      function saveForm() {
         hasUnsavedChanges = false;
         document.getElementById('status').textContent = 'Changes saved successfully!';
      }
   </script>
</body>
</html>

In this example, the warning appears only when there are unsaved changes. After clicking "Save Changes", the warning is disabled.

Conditional beforeunload Warning

You can conditionally show the unload warning based on specific conditions, such as unsaved form data or active processes.

Example

Following example shows a conditional warning based on user interaction −

<!DOCTYPE html>
<html>
<head>
   <title>Conditional beforeunload Warning</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Text Editor</h2>
   <textarea id="editor" rows="5" cols="50" placeholder="Start typing to enable unload warning..."></textarea><br><br>
   <button onclick="clearEditor()">Clear Text</button>
   <p id="status">No unsaved changes</p>

   <script>
      let isDirty = false;
      const editor = document.getElementById('editor');
      const status = document.getElementById('status');

      editor.addEventListener('input', function() {
         isDirty = true;
         status.textContent = 'You have unsaved changes';
         status.style.color = 'red';
      });

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

      function clearEditor() {
         editor.value = '';
         isDirty = false;
         status.textContent = 'No unsaved changes';
         status.style.color = 'green';
      }
   </script>
</body>
</html>

The warning only triggers after the user starts typing in the textarea. Clearing the text removes the warning condition.

beforeunload Event Flow User Action beforeunload Browser Dialog Stay/Leave Decision ? Close tab ? Refresh (F5) ? Navigate away Event fired Return string Shows warning (if prevented) User chooses to stay/leave

Important Browser Behavior Notes

Modern browsers have implemented several restrictions on the beforeunload event for security and user experience reasons −

  • Custom messages − Most browsers ignore custom return messages and show their own generic dialog text.

  • User activation required − The event only triggers if the user has interacted with the page (clicked, typed, etc.).

  • preventDefault() and returnValue − Both event.preventDefault() and setting event.returnValue = '' are needed for cross-browser compatibility.

  • No guaranteed execution − The browser may not wait for the event handler to complete, especially during force-close operations.

Common Use Cases

The beforeunload event is commonly used in the following scenarios −

Use Case Description
Form Protection Warn users about unsaved form data before leaving the page.
Text Editors Prevent accidental loss of document changes in online editors.
File Uploads Alert users if they try to leave during an active file upload.
Gaming Applications Warn about losing game progress when exiting a web-based game.
Data Synchronization Ensure data is saved to the server before the user leaves.

Conclusion

The onbeforeunload event provides a way to interact with users before they leave your page, helping prevent data loss and improve user experience. While modern browsers limit custom messages for security, the event remains effective for conditional warnings based on user interactions and unsaved changes.

Updated on: 2026-03-16T21:38:53+05:30

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements