HTML onbeforeunload Attribute

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

Introduction

The onbeforeunload attribute is an inline event handler that runs JavaScript when the beforeunload event fires. That event occurs on the window when the user tries to leave the page—closing the tab, reloading, or navigating to another URL. Use it to warn about unsaved changes so users do not lose work by accident. Modern browsers show a generic confirmation dialog and ignore custom message text for security. Use sparingly and only when data would be lost.

What You’ll Learn

01

Event handler

Inline JS.

02

beforeunload

Window event.

03

Leave page

Tab close / nav.

04

unsaved data

Main use case.

05

addEventListener

Preferred way.

06

.onbeforeunload

Property API.

Purpose of onbeforeunload Attribute

The primary purpose of onbeforeunload is to give users a chance to stay on the page when they might lose work. A typical pattern tracks whether a form or editor is “dirty” (modified but not saved) and only enables the leave warning when dirty === true. When the user saves, remove the listener or clear the dirty flag.

The old reference implied you could display any custom message in the dialog. Modern browsers ignore custom strings—Chrome, Firefox, and Safari show a generic confirmation instead. Returning a non-empty string or calling event.preventDefault() still triggers the prompt; the exact wording is controlled by the browser, not your script.

💡
Prefer addEventListener on window

Production code should use window.addEventListener("beforeunload", handler) with event.preventDefault(). Inline onbeforeunload on <body> works for learning but separates concerns less cleanly.

📝 Syntax

Set onbeforeunload on body or assign window.onbeforeunload:

onbeforeunload.html
<script>

  function handleLeave() {

    return "You may have unsaved changes.";

  }

</script>



<body onbeforeunload="return handleLeave()">

  <textarea id="draft"></textarea>

</body>

Syntax Rules

  • Value is JavaScript code executed when the beforeunload event fires.
  • Event target is window; body.onbeforeunload maps to the same event.
  • Legacy: return a non-empty string from the handler to trigger the dialog.
  • Modern: call event.preventDefault() and set event.returnValue = "".
  • JavaScript: window.onbeforeunload = function(e) { … }.
  • Modern alternative: window.addEventListener("beforeunload", handler).
  • Triggered by tab close, reload, back/forward navigation, or link to another page.

💎 Values

The onbeforeunload attribute accepts a string of JavaScript code:

  • onbeforeunload="return handleLeave()" — Call a function that returns a string.
  • onbeforeunload="return 'Leave?' " — Inline return (custom text ignored in modern browsers).
  • JavaScript: window.onbeforeunload = (e) => { e.preventDefault(); e.returnValue = ""; }.
onbeforeunload-js.html
var dirty = false;

document.getElementById("draft").addEventListener("input", () => { dirty = true; });

window.addEventListener("beforeunload", (event) => {

  if (!dirty) return;

  event.preventDefault();

  event.returnValue = "";

});

⚡ Quick Reference

EventWhen it firesHandler
beforeunloadUser tries to leave pageonbeforeunload
unloadPage is unloadingonunload
Trigger dialogreturn "" or preventDefault()Generic browser text
Unsaved changesEnable only when dirtyBest practice
Custom messageIgnored in modern browsersSecurity policy

Applicable Elements

TargetSupported?Notes
windowYesPrimary event target
<body>YesInline onbeforeunload attribute
<img>, <form>NoNot print events

onbeforeunload vs onunload

HandlerTimingTypical use
onbeforeunloadBefore page unloadsConfirm leave / unsaved changes
onunloadDuring unloadCleanup only — too late for dialogs

Examples Gallery

Inline onbeforeunload, addEventListener on window, and unsaved-changes-only pattern.

👀 Live Preview

Type in the draft below, then try reloading or closing this tab:

No leave warning until you type something.

Example — Inline onbeforeunload on body

Return a string when the user tries to leave:

inline-onbeforeunload.html
<body onbeforeunload="return handleLeave()">

  <textarea id="draft"></textarea>

</body>



<script>

  function handleLeave() {

    return "You may have unsaved changes.";

  }

</script>
Try It Yourself

How It Works

The browser fires beforeunload on window before navigation. The inline attribute on body wires up the same handler. Use return in the attribute value.

Dynamic Values with JavaScript

Attach the handler with addEventListener:

dynamic-onbeforeunload.html
<script>

  window.addEventListener("beforeunload", (event) => {

    event.preventDefault();

    event.returnValue = "";

  });



  // Or property form:

  window.onbeforeunload = function (e) { e.preventDefault(); e.returnValue = ""; };

</script>
Try It Yourself

How It Works

Register the listener once at page load. When the user tries to leave, the handler runs and may show the browser’s generic confirmation.

Example — Warn only for unsaved changes

Enable the leave warning only when a form field is dirty:

dirty-beforeunload.html
var dirty = false;

document.getElementById("draft").addEventListener("input", () => { dirty = true; });



window.addEventListener("beforeunload", (event) => {

  if (!dirty) return;

  event.preventDefault();

  event.returnValue = "";

});
Try It Yourself

How It Works

Track edits with a flag. Skip preventDefault when nothing changed so users can leave freely without annoying prompts.

♿ Accessibility

  • Use only for unsaved work — Do not block navigation when nothing would be lost.
  • Generic dialog text — Browsers control the message; ensure your in-page UI explains why leaving is risky.
  • Avoid alert() in handlers — Use the built-in beforeunload confirmation only; extra alerts trap focus.
  • Keyboard users — Leave warnings apply to all navigation paths including back button and tab close.
  • Do not abuse prompts — Frequent or marketing-driven warnings harm accessibility and trust.

🧠 How onbeforeunload Works

1

User tries to leave

Close tab, reload, or navigate.

Trigger
2

beforeunload fires

Handler runs on window.

onbeforeunload
3

Browser may prompt

If handler calls preventDefault.

Dialog
=

User decides

Stay or leave page.

Browser Support

The beforeprint event and onbeforeprint handler are supported in Chrome 63+, Firefox 6+, Safari 13+, and Edge 79+. Older browsers may not fire these events; rely on @media print CSS as a baseline.

DOM Events · Fully supported

Universal onbeforeunload support

All major browsers fire the underlying event and honor the onbeforeunload handler attribute.

98% Browser support
Google Chrome 63+
Full support
Mozilla Firefox 6+
Full support
Apple Safari 13+
Full support
Microsoft Edge 79+
Full support
Internet Explorer IE 9+ supported
Full support
Opera Fully supported
Full support
onbeforeunload attribute 98% supported

Bottom line: Widely supported in modern browsers. Test print preparation and cancel flows in your target browsers.

💡 Best Practices

✅ Do

  • Use addEventListener on window — Clearer than inline onbeforeprint.
  • Pair with afterprint — Every prepare step should have a matching restore step.
  • Prefer @media print CSS — Use JS events only when CSS alone is insufficient.
  • Keep handlers fast — Avoid heavy work blocking the UI before the dialog opens.
  • Hide screen-only chrome — Nav bars and toolbars are common beforeprint targets.

❌ Don’t

  • Do not assume print success — beforeprint runs even if the user later cancels.

Conclusion

The onbeforeprint attribute runs JavaScript when the print dialog opens and the beforeprint event fires on window. Use it to prepare the page for printing before the layout is rendered.

Pair it with onafterprint, prefer addEventListener("beforeprint", …), and remember the event means “print flow starting,” not “print succeeded.”

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onbeforeunload

Bookmark these before wiring your next event handler.

5
Core concepts
🌐 02

window target

Not img/form.

Scope
🔄 03

Prepare UI

Before afterprint.

Pattern
📝 04

addEventListener

Preferred.

Modern
05

Not success proof

Opens early.

Note

❓ Frequently Asked Questions

It runs JavaScript when the beforeprint event fires — when the print dialog opens or print preview starts.
No. It fires when the print dialog opens, before the user prints or cancels. Use it to prepare layout, not to confirm paper output.
On window via addEventListener("beforeprint", …). Inline onbeforeprint on body also works.
onbeforeprint runs when the dialog opens (prepare). onafterprint runs when it closes (restore).
Yes. @media print { … } handles most print styling without JavaScript. Use beforeprint when you need script-driven preparation.
Call window.print() or use the browser Print command. beforeprint fires as soon as the print UI opens.

Prepare pages for printing

Practice inline onbeforeprint, addEventListener, and afterprint pairing in the Try It editor.

Try onbeforeprint 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