JavaScript unload Event and Modern Page-Exit Alternatives

The unload event is a historical page-exit event. Older examples used it to run JavaScript when a user left a page or closed a tab. Modern browsers intentionally restrict and sometimes skip this event, so it should not be used for critical work.

Modern guidance: avoid unload for new code. Use visibilitychange for state saving, pagehide when you specifically need a page-hiding/navigation signal, and beforeunload only when a user has unsaved changes and genuinely needs a leave-page warning.

Open the page-exit demo in a new tab

Table of Contents

Original unload Pattern Top ↑

The original plus2net demonstration attached an inline onunload handler that attempted to show an alert. That source is preserved here for historical understanding, but the alert is not a dependable modern behavior because user-interface interactions are restricted during unloading.

<body onunload="alert('thanks for visiting plus2net')">
  You should get one alert message when you close or leave this page.
</body>

A JavaScript property/listener version of the same legacy event is:

window.addEventListener('unload', () => {
  // Do not rely on UI or long-running work here.
});

Why unload Is Unreliable Top ↑

Browsers may skip unload, particularly in mobile and back/forward-cache scenarios. Dialogs, new windows and other UI operations are ineffective while unloading. This means an exit alert is not a reliable feature to build around.

Use pagehide for Page Navigation Top ↑

If the purpose is to observe that a page is being hidden because another history entry is about to be shown, pagehide is a better fit and is compatible with the browser back/forward cache.

window.addEventListener('pagehide', (event) => {
  console.log(`Page hidden. Persisted in bfcache: ${event.persisted}`);
});

Use visibilitychange for Saving State Top ↑

For automatically saving application state when the user switches tabs/apps or the page becomes hidden, listen for visibilitychange.

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') {
    saveDraft();
  }
});

Use beforeunload Only for Unsaved Changes Top ↑

beforeunload can request a browser-generated leave-page confirmation. Modern browsers control the wording and generally require prior user interaction. Register it only while unsaved data exists, because persistent listeners can hurt navigation performance.

function warnAboutUnsavedChanges(event) {
  event.preventDefault();
  event.returnValue = true; // Legacy support
}

window.addEventListener('beforeunload', warnAboutUnsavedChanges);

Event Handling onMouseOver and onMouseOut




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer