👀 Live Preview
Type in the draft below, then try reloading or closing this tab:
No leave warning until you type something.

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.
Inline JS.
Window event.
Tab close / nav.
Main use case.
Preferred way.
Property API.
onbeforeunload AttributeThe 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.
Production code should use window.addEventListener("beforeunload", handler) with event.preventDefault(). Inline onbeforeunload on <body> works for learning but separates concerns less cleanly.
Set onbeforeunload on body or assign window.onbeforeunload:
<script>
function handleLeave() {
return "You may have unsaved changes.";
}
</script>
<body onbeforeunload="return handleLeave()">
<textarea id="draft"></textarea>
</body>beforeunload event fires.window; body.onbeforeunload maps to the same event.event.preventDefault() and set event.returnValue = "".window.onbeforeunload = function(e) { … }.window.addEventListener("beforeunload", handler).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).window.onbeforeunload = (e) => { e.preventDefault(); e.returnValue = ""; }.var dirty = false;
document.getElementById("draft").addEventListener("input", () => { dirty = true; });
window.addEventListener("beforeunload", (event) => {
if (!dirty) return;
event.preventDefault();
event.returnValue = "";
});| Event | When it fires | Handler |
|---|---|---|
beforeunload | User tries to leave page | onbeforeunload |
unload | Page is unloading | onunload |
| Trigger dialog | return "" or preventDefault() | Generic browser text |
| Unsaved changes | Enable only when dirty | Best practice |
| Custom message | Ignored in modern browsers | Security policy |
| Target | Supported? | Notes |
|---|---|---|
window | Yes | Primary event target |
<body> | Yes | Inline onbeforeunload attribute |
<img>, <form> | No | Not print events |
onbeforeunload vs onunload| Handler | Timing | Typical use |
|---|---|---|
onbeforeunload | Before page unloads | Confirm leave / unsaved changes |
onunload | During unload | Cleanup only — too late for dialogs |
Inline onbeforeunload, addEventListener on window, and unsaved-changes-only pattern.
Type in the draft below, then try reloading or closing this tab:
No leave warning until you type something.
Return a string when the user tries to leave:
<body onbeforeunload="return handleLeave()">
<textarea id="draft"></textarea>
</body>
<script>
function handleLeave() {
return "You may have unsaved changes.";
}
</script>The browser fires beforeunload on window before navigation. The inline attribute on body wires up the same handler. Use return in the attribute value.
Attach the handler with addEventListener:
<script>
window.addEventListener("beforeunload", (event) => {
event.preventDefault();
event.returnValue = "";
});
// Or property form:
window.onbeforeunload = function (e) { e.preventDefault(); e.returnValue = ""; };
</script>Register the listener once at page load. When the user tries to leave, the handler runs and may show the browser’s generic confirmation.
Enable the leave warning only when a form field is dirty:
var dirty = false;
document.getElementById("draft").addEventListener("input", () => { dirty = true; });
window.addEventListener("beforeunload", (event) => {
if (!dirty) return;
event.preventDefault();
event.returnValue = "";
});Track edits with a flag. Skip preventDefault when nothing changed so users can leave freely without annoying prompts.
Close tab, reload, or navigate.
Handler runs on window.
If handler calls preventDefault.
Stay or leave page.
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.
onbeforeunload supportAll major browsers fire the underlying event and honor the onbeforeunload handler attribute.
Bottom line: Widely supported in modern browsers. Test print preparation and cancel flows in your target browsers.
onbeforeprint.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.”
onbeforeunloadBookmark these before wiring your next event handler.
beforeprint fires.
EventNot img/form.
ScopeBefore afterprint.
PatternPreferred.
ModernOpens early.
Notebeforeprint event fires — when the print dialog opens or print preview starts.window via addEventListener("beforeprint", …). Inline onbeforeprint on body also works.onbeforeprint runs when the dialog opens (prepare). onafterprint runs when it closes (restore).@media print { … } handles most print styling without JavaScript. Use beforeprint when you need script-driven preparation.window.print() or use the browser Print command. beforeprint fires as soon as the print UI opens.Practice inline onbeforeprint, addEventListener, and afterprint pairing in the Try It editor.
5 people found this page helpful