HTML onunload Attribute

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

Definition and Usage

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.

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).

Attribute Values

The attribute value is always a script. Study patterns (prefer alternatives in apps):

Value / patternDescriptionTry it
scriptAny JavaScript run on unload (legacy)Try it
localStorage saveQuick sync write before teardownTry it
sendBeaconClassic analytics pattern — better on hideTry it
Prefer pagehideSafer sibling for leaving the pageTry it

Live Preview

unload cannot be demoed safely without leaving the page — and many browsers skip it. This preview uses the preferred visibilitychange 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…

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>
Try It Yourself

How It Works

  1. Put onunload on <body> (window-level handler).
  2. User leaves the page (navigate, close, reload) — if the browser still fires unload.
  3. Keep work tiny — sync localStorage only; no dialogs.
  4. 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>
Try It Yourself

How It Works

  1. Listen for visibilitychange on document.
  2. When visibilityState === "hidden", the page is no longer visible.
  3. Send or save then — last reliable moment for many apps.
  4. Skip unload so bfcache and mobile behavior stay healthier.

Example 3 — pagehide Instead of unload

Use pagehide when you care about navigating away in history.

HTML
<p id="status">Navigate away or use Back/Forward in tryit.</p>

<script>
  window.addEventListener("pagehide", function (event) {
    document.getElementById("status").textContent =
      "pagehide — persisted=" + event.persisted;
    try {
      sessionStorage.setItem("pagehideAt", String(Date.now()));
    } catch (e) {}
  });
</script>
Try It Yourself

How It Works

  1. pagehide fires when the browser hides the page for another history entry.
  2. event.persisted is true if the page may enter bfcache.
  3. Still not perfect on mobile — MDN still prefers visibilitychange when possible.
  4. 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.

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.

Legacy Use with caution
Google Chrome Modern
Unload often not fired by default
Mozilla Firefox All modern
Supported (bfcache impact)
Apple Safari All modern
Supported (mobile limits)
Microsoft Edge Modern
Same Chromium policy trend
Opera Modern
Chromium-based
Samsung Internet Modern
Mobile unload unreliable
Internet Explorer All
Supported (legacy)
onunload Avoid for new apps

Bottom line: Know the syntax for exams and legacy code. For real sites, use visibilitychange (hidden) or pagehide — not onunload.

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.

Next: onvolumechange

Run JavaScript when media volume or muted state changes.

onvolumechange tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful