Course contentsShow
← Web Development
Lesson 968 of 2,98217. URL and History ManagementFree lesson

Preventing Unintended Navigation with beforeunload

Warning users about unsaved changes before they navigate away from the page.

Preventing Unintended Navigation with beforeunload

What you'll learn: How to warn users when they're about to lose unsaved work by navigating away from your page.

The Problem

Imagine a user fills out a lengthy form or composes a detailed message, then accidentally clicks a link or presses the back button. All their work vanishes. The beforeunload event gives you one chance to warn them before it's too late.

How beforeunload Works

The beforeunload event fires when the user is about to leave your page—whether by closing the tab, navigating to another URL, or reloading. You can intercept this moment and trigger the browser's built-in confirmation dialog.

Important limitation: For security reasons, you cannot customize the warning message text in modern browsers. The browser shows its own generic message like "Changes you made may not be saved."

Basic Implementation

// Track whether the user has unsaved changes
let hasUnsavedChanges = false;

// Set flag when user makes changes
document.getElementById('myForm').addEventListener('input', () => {
  hasUnsavedChanges = true;
});

// Warn before leaving if there are unsaved changes
window.addEventListener('beforeunload', (event) => {
  if (hasUnsavedChanges) {
    // Modern way: prevent default and set returnValue
    event.preventDefault();
    event.returnValue = ''; // Required for some browsers
  }
});

// Clear flag after successful save
function onSaveSuccess() {
  hasUnsavedChanges = false;
}

When to Use It

Only trigger beforeunload when truly necessary. False alarms frustrate users. Track actual changes, and clear your flag after successful saves or form submissions.

Key Takeaway: The beforeunload event lets you prevent accidental data loss by triggering a browser warning when users attempt to navigate away with unsaved changes—just set event.preventDefault() and event.returnValue conditionally.