HTML onbeforeunload Attribute

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

Definition and Usage

The onbeforeunload attribute handles the window beforeunload event. It runs when the document is about to unload — close, reload, or navigate away — while the page is still visible.

Put it on <body>, or use window.addEventListener("beforeunload", …). Warn only about unsaved changes, then remove the listener when nothing is dirty.

Limited availability.

MDN: not Baseline across all major browsers. Support and dialog behavior vary; do not rely on it alone to save data.

Inline handlers discouraged.

Prefer addEventListener. Call event.preventDefault() (and set event.returnValue for legacy). Browsers show a generic message — custom strings are ignored.

HTML Syntax

syntax.html
<body onbeforeunload=" script">

script runs when beforeunload fires. Preferred: window.addEventListener("beforeunload", handler) with preventDefault().

Attribute Values

How you listen for beforeunload:

Value / formDescriptionTry it
JavaScript on bodyInline handler (study form; prefer listeners)Try it
addEventListener("beforeunload")preventDefault() + returnValue (recommended)Try it
Dirty-only listenerAttach only when a field has unsaved textTry it

Live Preview

Enable a leave warning for this tab, then try reload or close. Disable when done so you can leave this tutorial freely.

warning

Requires a prior click on this page (sticky activation). Dialog text is browser-controlled.

Demo

Leave warning is off.

HTML Examples

Short study snippets. Use Try It Yourself, then reload that editor tab. Prefer listeners and dirty-only attachment in real apps.

Example 1 — Inline onbeforeunload on body

Recognize the attribute form. Returning a string is a legacy trigger for the property/attribute style.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>onbeforeunload demo</title>
</head>
<body onbeforeunload="return 'You have unsaved changes.';">
  <p>Reload or close this tab to see the browser leave dialog.</p>
</body>
</html>
Try It Yourself

How It Works

  1. onbeforeunload on body registers a window-level handler.
  2. return "…" is a legacy way to request the leave dialog (property/attribute only).
  3. Unload attempt (reload/close/navigate) may show a generic browser prompt.
  4. Custom text is not shown in modern browsers.

Example 2 — Preferred addEventListener

MDN pattern: preventDefault() plus returnValue for older engines.

HTML
<p id="status">Listener attached. Reload this page to test.</p>

<script>
  window.addEventListener("beforeunload", function (event) {
    event.preventDefault();
    // Legacy support (e.g. older Chromium)
    event.returnValue = true;
  });
</script>
Try It Yourself

How It Works

  1. Listener on window — no inline attribute.
  2. preventDefault() asks the browser to show the confirmation.
  3. returnValue covers older Chromium-style support.
  4. Returning a string does not work with addEventListener.

Example 3 — Warn only with unsaved changes

Attach the handler when the field is non-empty; remove it when cleared.

HTML
<label for="name">Draft note</label>
<input type="text" id="name" name="name" autocomplete="off">
<p id="status">No unsaved text — leave freely.</p>

<script>
  function beforeUnloadHandler(event) {
    event.preventDefault();
    event.returnValue = true;
  }

  var input = document.getElementById("name");
  var status = document.getElementById("status");

  input.addEventListener("input", function () {
    if (input.value !== "") {
      window.addEventListener("beforeunload", beforeUnloadHandler);
      status.textContent = "Unsaved text — reload may warn.";
    } else {
      window.removeEventListener("beforeunload", beforeUnloadHandler);
      status.textContent = "No unsaved text — leave freely.";
    }
  });
</script>
Try It Yourself

How It Works

  1. Named handler so you can remove the same function later.
  2. On input — non-empty value adds beforeunload.
  3. Empty again — remove the listener so exit is quiet.
  4. Best practice — warn only when there is real data to lose.

Edge Cases & Pitfalls

Browsers limit this event to stop spammy leave prompts.

message

No custom dialog text

Modern browsers show a generic string. Your return value does not appear as the prompt.

activation

Needs user interaction

Sticky activation: if the user never interacted with the page, the dialog usually will not show.

mobile

Not reliable on mobile

Closing via the app switcher may skip beforeunload. Save important state earlier — do not depend on this event alone.

attach

Attach only when dirty

Permanent listeners annoy users. Add when unsaved; remove after save or clear.

style

Prefer listeners

Inline on* attributes mix concerns. Use addEventListener with preventDefault() in production.

Browser Support

onbeforeunload is a window event handler for beforeunload. Dialog rules and reliability vary by browser and platform.

✓ Limited availability

onbeforeunload

Works in major desktop browsers with restrictions (generic dialog, sticky activation). Mobile unload paths are less reliable. Not marked Baseline by MDN.

Varies Support &amp; behavior
Google Chrome Modern
Supported*
Mozilla Firefox Modern
Supported*
Apple Safari Modern
Supported*
Microsoft Edge Modern
Supported*
Opera Modern
Supported*
Samsung Internet Modern
Partial*
Internet Explorer Legacy*
Supported*
beforeunload Limited / restricted

Bottom line: *Dialogs are generic and often require prior user interaction. Prefer dirty-only listeners; save state without relying only on beforeunload.

Key Takeaways

  • Role: optional leave/reload confirmation for unsaved work.
  • Trigger: preventDefault() (+ returnValue legacy).
  • Prefer: dirty-only addEventListener, not always-on.
  • Limits: generic message; weak on some mobile exits.

One line: onbeforeunload can warn before leave — attach only when dirty, expect a generic dialog, and save data elsewhere too.

Frequently Asked Questions

It is an event handler for the beforeunload event. That event fires when the window or document is about to unload (close, reload, or navigate away). Sites use it to show a browser confirmation when there may be unsaved data.
It is a window-level handler. In HTML, put it on body (window handlers on body listen on window), or use window.addEventListener("beforeunload", …) / window.onbeforeunload.
No. Modern browsers show a generic dialog. Custom return strings are ignored for the visible text.
Best practice: call event.preventDefault() and also set event.returnValue for older browsers. Returning a string only works with the onbeforeunload property, not addEventListener.
Only while there are unsaved changes. Add the listener when the page becomes dirty; remove it when data is saved or cleared. MDN also notes sticky activation: the user must have interacted with the page.
Not always. Closing the browser from the app switcher may skip beforeunload. Prefer saving important state earlier (for example on visibility changes) instead of relying only on this event.

Next: onblur

Handle when an element loses focus.

onblur 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