👀 Live Preview
Reload this section’s demo logic — a counter in sessionStorage proves unload ran:
Checking unload demo state…
Reload the full page to trigger unload on this tutorial — the try-it editor demos show the pattern interactively.

The onunload handler runs JavaScript when the unload event fires on window — when the user navigates away, reloads, or closes the tab and the document is being torn down. Use it for quick cleanup: save a draft to localStorage, clear timers, or send analytics with navigator.sendBeacon. It runs too late for confirmation dialogs — use onbeforeunload for leave warnings. Prefer addEventListener("unload", …) in production, and consider pagehide for modern apps.
Page leave.
Teardown.
Warn vs cleanup.
Analytics.
localStorage.
Preferred way.
onunload AttributeThe primary purpose of onunload is to run last-moment tasks when a page session ends — saving unsent form text, flushing analytics, or releasing resources. The browser gives handlers very little time; keep work short and synchronous.
Unlike beforeunload, you cannot prompt the user to stay. By the time unload fires, the user has already chosen to leave. For “unsaved changes” warnings, use onbeforeunload instead.
Async fetch may be cancelled during unload. Use navigator.sendBeacon() for outbound data or synchronous localStorage for small drafts.
Assign the handler on window — the event target for page unload:
<body onunload="performUnloadActions()">
<!-- page content -->
</body>
<script>
window.onunload = performUnloadActions;
window.addEventListener("unload", performUnloadActions);
</script>window; <body onunload> is a legacy HTML shortcut.unload event fires.beforeunload for that.window.onunload = function() { … }.window.addEventListener("unload", handler).The onunload property accepts a function or function reference:
onunload="performUnloadActions()" — Call a named function on body.window.onunload = performUnloadActions — Property assignment.window.addEventListener("unload", handler).function performUnloadActions() {
// Sync save — reliable during unload
localStorage.setItem("draft", noteInput.value);
// Analytics — sendBeacon survives page teardown
navigator.sendBeacon("/analytics", JSON.stringify({ left: true }));
}
window.addEventListener("unload", performUnloadActions);| Event / API | When it runs | Notes |
|---|---|---|
unload | Document tearing down | onunload |
beforeunload | Before leave (cancellable) | Leave confirmation |
pagehide | Page hidden (bfcache) | Modern alternative |
visibilitychange | Tab hidden/shown | Pause work, not full unload |
navigator.sendBeacon() | During unload | Reliable analytics POST |
localStorage.setItem | Sync during unload | Small draft saves |
| Target | Supported? | Notes |
|---|---|---|
window | Yes | Primary and correct target |
window.addEventListener("unload") | Yes | Recommended registration |
<body onunload> | Yes (legacy) | Maps to window unload in practice |
<form>, <input> | No | Not an element-level event |
<iframe> content | Separate | Each document has its own unload |
onunload vs onbeforeunload vs pagehide| Handler | When it fires | Typical use |
|---|---|---|
onbeforeunload | Before page unloads | “Unsaved changes” warning |
onunload | During document teardown | Quick cleanup, sendBeacon |
pagehide | Page leaves view (incl. bfcache) | Modern session end handling |
visibilitychange | Tab visibility changes | Pause timers, save state |
Inline body handler with sessionStorage timestamp, dynamic window.onunload, and addEventListener draft save.
Reload this section’s demo logic — a counter in sessionStorage proves unload ran:
Checking unload demo state…
Reload the full page to trigger unload on this tutorial — the try-it editor demos show the pattern interactively.
Save a timestamp when the page unloads — visible after reload:
<body onunload="performUnloadActions()">
<p id="status"></p>
<script>
function performUnloadActions() {
sessionStorage.setItem("lastUnload", new Date().toLocaleTimeString());
}
status.textContent = sessionStorage.getItem("lastUnload") || "Reload to test";
</script>
</body>When the document unloads, performUnloadActions() writes to sessionStorage. On the next load, your script reads it back — proof the handler ran.
Assign the handler on window at runtime:
<script>
window.onunload = function () {
sessionStorage.setItem("dynamicUnload", Date.now().toString());
};
</script>window.onunload is equivalent to the inline body attribute. Attach after the page loads when you need conditional unload behavior.
Persist textarea content synchronously when the user leaves:
window.addEventListener("unload", function () {
localStorage.setItem("draft", noteInput.value);
});
// On next visit:
noteInput.value = localStorage.getItem("draft") || "";Synchronous localStorage writes are among the few reliable operations during unload. Pair with periodic saves while the user types for better UX.
unload cannot show accessible custom dialogs; use beforeunload sparingly for leave warnings.aria-live.beforeunload with care.Navigate / close.
Optional warn.
onunload runs.
Beacon, draft save.
The unload event is supported in all browsers, but mobile and modern browsers may limit how much work runs. Prefer pagehide and proactive saves for critical data.
onunload supportAll browsers fire unload, but keep handlers minimal — behavior varies on mobile.
Bottom line: Supported everywhere, but treat it as a last-chance hook — not your only save strategy.
navigator.sendBeacon() for analytics on leaveinput too, not only unloadonbeforeunload for leave confirmationsaddEventListener("unload", …) on windowonunloadunload with beforeunloadThe onunload attribute runs JavaScript when the page session ends — useful for quick cleanup, draft saves, and analytics beacons when the user navigates away.
Use beforeunload for warnings, keep handlers fast, save data proactively, and prefer addEventListener on window in production.
onunloadBookmark these before wiring page-leave handlers.
Page leave.
WhereNo dialogs.
WhenWarn first.
CompareAnalytics.
APISave early.
Gotchaunload event fires — when the document is being torn down because the user navigated away, reloaded, or closed the tab.onbeforeunload runs before leave and can trigger a confirmation dialog. onunload runs during teardown — too late for prompts, good for quick cleanup.navigator.sendBeacon() for small outbound payloads during unload.window. In JavaScript, use window.onunload or window.addEventListener("unload", …).window.addEventListener("unload", handler) is preferred. For new projects, also evaluate pagehide for bfcache-friendly behavior.Practice the onunload attribute with timestamp and draft-save demos in the Try It editor.
5 people found this page helpful