HTML onunload Attribute

Beginner
⏱️ 6 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

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.

What You’ll Learn

01

Window handler

Page leave.

02

unload

Teardown.

03

vs beforeunload

Warn vs cleanup.

04

sendBeacon

Analytics.

05

Sync save

localStorage.

06

addEventListener

Preferred way.

Purpose of onunload Attribute

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

💡
Keep handlers fast

Async fetch may be cancelled during unload. Use navigator.sendBeacon() for outbound data or synchronous localStorage for small drafts.

📝 Syntax

Assign the handler on window — the event target for page unload:

onunload.html
<body onunload="performUnloadActions()">
  <!-- page content -->
</body>

<script>
  window.onunload = performUnloadActions;
  window.addEventListener("unload", performUnloadActions);
</script>

Syntax Rules

  • Target is window; <body onunload> is a legacy HTML shortcut.
  • Value is JavaScript executed when the unload event fires.
  • Triggered by navigation, reload, tab close, and some back/forward moves.
  • Cannot show custom leave dialogs — use beforeunload for that.
  • Keep handlers fast; avoid long loops or async work that may not finish.
  • JavaScript: window.onunload = function() { … }.
  • Modern alternative: window.addEventListener("unload", handler).

💎 Values

The onunload property accepts a function or function reference:

  • onunload="performUnloadActions()" — Call a named function on body.
  • window.onunload = performUnloadActions — Property assignment.
  • Preferred: window.addEventListener("unload", handler).
onunload-handler.js
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);

⚡ Quick Reference

Event / APIWhen it runsNotes
unloadDocument tearing downonunload
beforeunloadBefore leave (cancellable)Leave confirmation
pagehidePage hidden (bfcache)Modern alternative
visibilitychangeTab hidden/shownPause work, not full unload
navigator.sendBeacon()During unloadReliable analytics POST
localStorage.setItemSync during unloadSmall draft saves

Applicable Elements

TargetSupported?Notes
windowYesPrimary and correct target
window.addEventListener("unload")YesRecommended registration
<body onunload>Yes (legacy)Maps to window unload in practice
<form>, <input>NoNot an element-level event
<iframe> contentSeparateEach document has its own unload

onunload vs onbeforeunload vs pagehide

HandlerWhen it firesTypical use
onbeforeunloadBefore page unloads“Unsaved changes” warning
onunloadDuring document teardownQuick cleanup, sendBeacon
pagehidePage leaves view (incl. bfcache)Modern session end handling
visibilitychangeTab visibility changesPause timers, save state

Examples Gallery

Inline body handler with sessionStorage timestamp, dynamic window.onunload, and addEventListener draft save.

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

Example — onunload on body

Save a timestamp when the page unloads — visible after reload:

body-onunload.html
<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>
Try It Yourself

How It Works

When the document unloads, performUnloadActions() writes to sessionStorage. On the next load, your script reads it back — proof the handler ran.

Dynamic Values with JavaScript

Assign the handler on window at runtime:

dynamic-onunload.html
<script>
  window.onunload = function () {
    sessionStorage.setItem("dynamicUnload", Date.now().toString());
  };
</script>
Try It Yourself

How It Works

window.onunload is equivalent to the inline body attribute. Attach after the page loads when you need conditional unload behavior.

Example — Save draft on unload

Persist textarea content synchronously when the user leaves:

unload-draft-save.html
window.addEventListener("unload", function () {
  localStorage.setItem("draft", noteInput.value);
});

// On next visit:
noteInput.value = localStorage.getItem("draft") || "";
Try It Yourself

How It Works

Synchronous localStorage writes are among the few reliable operations during unload. Pair with periodic saves while the user types for better UX.

♿ Accessibility

  • Do not trap usersunload cannot show accessible custom dialogs; use beforeunload sparingly for leave warnings.
  • Save work proactively — Relying only on unload may lose data for users with assistive tech or mobile tab discard.
  • Avoid blocking operations — Long unload handlers harm everyone, especially on slow devices.
  • Announce autosave in UI — If drafts restore on return, show a clear “Draft restored” message with aria-live.
  • Respect user intent — Never use unload handlers to prevent leaving — that belongs in beforeunload with care.

🧠 How onunload Works

1

User leaves

Navigate / close.

Trigger
2

beforeunload?

Optional warn.

Earlier
3

unload fires

onunload runs.

Event
=

Quick cleanup

Beacon, draft save.

Browser Support

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.

Window events · Universal support

Universal onunload support

All browsers fire unload, but keep handlers minimal — behavior varies on mobile.

99% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Limited on iOS
Microsoft Edge Fully supported
Full support
Internet Explorer Supported
Full support
Opera Fully supported
Full support
onunload attribute 99% supported

Bottom line: Supported everywhere, but treat it as a last-chance hook — not your only save strategy.

💡 Best Practices

✅ Do

  • Keep unload handlers short and synchronous
  • Use navigator.sendBeacon() for analytics on leave
  • Save drafts on input too, not only unload
  • Use onbeforeunload for leave confirmations
  • Prefer addEventListener("unload", …) on window

❌ Don’t

  • Run slow or async-only work in onunload
  • Show custom dialogs during unload — too late
  • Rely on unload as the only data-save mechanism
  • Block the browser with long loops on leave
  • Confuse unload with beforeunload

Conclusion

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

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onunload

Bookmark these before wiring page-leave handlers.

5
Core concepts
02

Too late

No dialogs.

When
03

beforeunload

Warn first.

Compare
📡 04

sendBeacon

Analytics.

API
05

Not async

Save early.

Gotcha

❓ Frequently Asked Questions

It runs JavaScript when the unload 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.
Often unreliable — the request may be cancelled. Use navigator.sendBeacon() for small outbound payloads during unload.
Both work in HTML, but the event target is 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.
Yes, but mobile browsers may skip or shorten unload work. Never depend on unload alone for critical data persistence.

Handle page leave gracefully

Practice the onunload attribute with timestamp and draft-save demos in the Try It editor.

Try unload timestamp demo →

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.

5 people found this page helpful