Events

onbeforeunload

A document is about to be unloaded, and a listener may request a browser confirmation prompt. Window event handler, exposed through the body element in HTML; register on window rather than on an arbitrary element. Event interface: BeforeUnloadEvent. For the described native event: bubbles: no; cancelable: yes. Only register while unsaved changes exist. A prompt needs prior user interaction; custom text is ignored and mobile delivery is unreliable. Example: Navigate away from a standalone page. The log is transient and may not remain visible. This example does not request a confirmation or perform cleanup. The event listener is registered with addEventListener(), which avoids inline script handlers and supports multiple listeners. Inline handlers require a CSP that permits them; do not insert untrusted code into handler attributes.

Formal Syntax & Structure

html syntaxhtml
<body onbeforeunload="handleEvent(event)">  window.addEventListener("beforeunload", event => { /* handle event */ });

Parameters & Attributes

NameTypeDescription
onbeforeunloadJavaScript handler bodyOptional HTML event-handler code; the example uses a registered listener instead. Not a Boolean attribute.
eventBeforeUnloadEventEvent object delivered to the addEventListener callback; event.type is "beforeunload". Inspect target, currentTarget, bubbles and cancelable as appropriate.

Working Example

Example Snippethtml
<p>Window event monitor</p><p role="status" id="log">Waiting for beforeunload</p><script>  const target = window;  const log = document.getElementById("log");  target.addEventListener("beforeunload", event => {    log.textContent = String(event.type);  });</script>
HTML Reference