Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onbeforeunload — handle an event before leaving a page

The onbeforeunload attribute on body sets a handler for the Window object's beforeunload event. It can request a warning before leaving the page, but it guarantees neither a dialog nor cancellation of navigation.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

<body onbeforeunload="event.preventDefault()">

onbeforeunload is an event handler attribute on body. Its value is JavaScript code, not an event name or a Boolean. It handles the Window object's beforeunload event, not an event targeting body itself. The corresponding JavaScript property is window.onbeforeunload.

During a real page departure, the handler can call event.preventDefault() to request confirmation. A legacy mechanism sets event.returnValue to a nonempty string. A special rule for onbeforeunload also allows returning a value other than null or undefined to cancel the event; do not transfer the usual return false pattern here. The return value of a function passed to addEventListener() does not work this way.

Canceling the event does not guarantee that navigation stops: the browser decides whether to show confirmation, and the user can choose to leave. A dialog requires prior user activation and may be suppressed by browser restrictions. You cannot set custom warning text. Enable the handler only for unsaved changes and remove it after saving; do not treat it as a guaranteed data-saving mechanism.

The example dispatches a synthetic, cancelable event to window and checks event.defaultPrevented. The expected output is true. It does not test real navigation or a dialog; it then removes the attribute so that no active handler remains.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>onbeforeunload wiring test</title>
</head>
<body onbeforeunload="event.preventDefault()">
  <p>See the browser console.</p>
  <script>
    const event = new Event('beforeunload', { cancelable: true });
    window.dispatchEvent(event);
    console.log(event.defaultPrevented);
    document.body.removeAttribute('onbeforeunload');
  </script>
</body>
</html>

Result

true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources