onunload
A document is being unloaded in environments that still deliver this legacy event. Window event handler, exposed through the body element in HTML; register on window rather than on an arbitrary element. Event interface: Event. For the described native event: bubbles: no; cancelable: no. Deprecated and unreliable; use visibilitychange or pagehide as appropriate, and avoid blocking the back-forward cache. 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
<body onunload="handleEvent(event)"> window.addEventListener("unload", event => { /* handle event */ });Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| onunload | JavaScript handler body | Optional HTML event-handler code; the example uses a registered listener instead. Not a Boolean attribute. |
| event | Event | Event object delivered to the addEventListener callback; event.type is "unload". Inspect target, currentTarget, bubbles and cancelable as appropriate. |
Working Example
<p>Window event monitor</p><p role="status" id="log">Waiting for unload</p><script> const target = window; const log = document.getElementById("log"); target.addEventListener("unload", event => { log.textContent = String(event.type); });</script>