The onunload attribute is a window-level event-handler (often written on <body>). It runs JavaScript when the unload event fires — the document (or a child resource) is being unloaded.
Order (per MDN): beforeunload → pagehide → unload. Related safer patterns: visibilitychange (when the page becomes hidden) and onpagehide.
Warning — avoid in new code.
MDN: developers should avoid unload. It is unreliable on mobile, can block the back/forward cache (bfcache), and Chrome has stopped firing it by default. Prefer visibilitychange (hidden) or pagehide.
Discouraged as inline HTML.
MDN also discourages HTML event handler attributes. Prefer addEventListener on the recommended lifecycle events — not <body onunload> — in production.
Syntax
HTML Syntax
syntax.html
<body onunload="script">
script is JavaScript that runs during unload (when the browser still fires it). Equivalent JS: window.onunload = handler or window.addEventListener("unload", handler).
Values
Attribute Values
The attribute value is always a script. Study patterns (prefer alternatives in apps):
unload cannot be demoed safely without leaving the page — and many browsers skip it. This preview uses the preferredvisibilitychange pattern: switch tabs or minimize to see “hidden”.
Lifecycle
Also listens for pagehide. Unload itself is intentionally not registered here.
Log
Waiting — switch tabs to fire visibilitychange…
Code
HTML Examples
Short study snippets. Prefer examples 2–3 for real apps. Use Try It Yourself for a live editor.
Example 1 — body onunload (Learn the Syntax)
Legacy pattern: save a draft flag when unload fires (may not run).
HTML
<body onunload="onLeave()">
<p>Leave or reload this tryit page to test unload (may be skipped).</p>
<p id="hint">Last leave: <span id="last">—</span></p>
<script>
function onLeave() {
try {
localStorage.setItem("leftAt", String(Date.now()));
} catch (e) {}
}
var last = localStorage.getItem("leftAt");
if (last) {
document.getElementById("last").textContent =
new Date(Number(last)).toLocaleString();
}
</script>
</body>
Open Try It Yourself — leave/reload that editor page to test. Unload may not fire in modern Chrome.
How It Works
Put onunload on <body> (window-level handler).
User leaves the page (navigate, close, reload) — if the browser still fires unload.
Keep work tiny — sync localStorage only; no dialogs.
Do not rely on it — many modern browsers skip or limit unload.
Example 2 — Prefer visibilitychange + sendBeacon
MDN’s recommended approach for analytics when the page becomes hidden.
HTML
<p id="log">Switch tabs or minimize to mark “hidden”.</p>
<script>
document.addEventListener("visibilitychange", function () {
if (document.visibilityState === "hidden") {
document.getElementById("log").textContent =
"hidden — good place for sendBeacon / save state.";
// navigator.sendBeacon("/log", "left");
}
});
</script>
Open Try It Yourself to navigate away and observe pagehide.
How It Works
pagehide fires when the browser hides the page for another history entry.
event.persisted is true if the page may enter bfcache.
Still not perfect on mobile — MDN still prefers visibilitychange when possible.
Better than unload for bfcache-friendly pages.
Edge Cases & Pitfalls
Most production bugs are trusting unload for analytics or cleanup that never runs.
mobile
Often skipped on mobile
Per MDN: switch apps then kill the browser — unload may never fire.
bfcache
Breaks or blocks bfcache
Unload listeners make some browsers refuse the back/forward cache, hurting Back-button performance.
chrome
Chrome default: no unload
Chrome stopped firing unload by default. Sites that still depend on it need a Permissions-Policy unload opt-in — better to migrate off.
ui
No alerts / opens
During unload, UI interactions are ineffective (alert, confirm, window.open). Use onbeforeunload for leave prompts.
frames
Parent before child
Unload follows the document tree: parent frame unload happens before child frame unload.
Compatibility
Browser Support
onunload is a window / body event-handler in the browser. It is not a Node.js, Deno, or Bun API.
✓ Supported but discouraged
onunload
Historically available everywhere, but unreliable in practice. Prefer visibilitychange / pagehide. Chrome may not fire unload by default.
LegacyUse with caution
Google ChromeModern
Unload often not fired by default
Mozilla FirefoxAll modern
Supported (bfcache impact)
Apple SafariAll modern
Supported (mobile limits)
Microsoft EdgeModern
Same Chromium policy trend
OperaModern
Chromium-based
Samsung InternetModern
Mobile unload unreliable
Internet ExplorerAll
Supported (legacy)
onunloadAvoid for new apps
Bottom line: Know the syntax for exams and legacy code. For real sites, use visibilitychange (hidden) or pagehide — not onunload.
Remember
Key Takeaways
Role: document is unloading (legacy lifecycle hook).
MDN: avoid unload in new projects.
Prefer:visibilitychange (hidden) or pagehide.
Prompts: use onbeforeunload, not onunload.
One line: learn onunload for legacy HTML — then ship visibilitychange / pagehide instead.
Frequently Asked Questions
It is a window-level event-handler attribute (often written on body). When the document is being unloaded, the unload event fires and the JavaScript in onunload runs — after beforeunload and pagehide.
MDN says developers should avoid unload. It is unreliable on mobile, hurts the back/forward cache (bfcache), and Chrome has stopped firing it by default. Prefer visibilitychange when the page becomes hidden, or pagehide for history navigation cases.
On window (window.onunload) or as an attribute on body (and historically frameset). The handler is a window-level event, not for input or button elements.
beforeunload runs earlier and can be used for a leave confirmation. unload runs later during teardown — too late for prompts, and UI like alert is ineffective.
Async work is often canceled. For small analytics, navigator.sendBeacon is the classic pattern — but prefer running that on visibilitychange (hidden) instead of unload.
It is still in the HTML specification, but MDN strongly warns against using it. Treat it as legacy knowledge: understand the syntax, then use safer lifecycle events in real apps.