CKTIS / HTML
onunload — handling document unloading
The body element's onunload attribute sets a handler for the Window object's unload event, not an event handler targeting the element itself. It is neither a reliable place to save data nor a way to prevent leaving a page.
Version: WHATWG HTML Living Standard; index snapshot date recorded separately
Syntax
<body onunload="/* JavaScript */">
window.onunload = handler;
window.onunload = null;onunload is an event handler content attribute for unload. On the body element, its value contains JavaScript executed as a handler on the associated Window object. It is not an ordinary global attribute for arbitrary HTML elements.
Its JavaScript counterpart is window.onunload, which accepts a function or null. The body attribute and this property control the same handler: another assignment replaces the previous value, and null removes it. Within the attribute's code, the event parameter provides the event.
unload concerns document unloading, but do not assume it occurs whenever a page is left. The standard's algorithm skips it when the document is kept for later restoration from history. Do not make it the only place that saves important data or rely on asynchronous work completing there. For lifecycle observation, consider pagehide or visibilitychange, depending on your purpose.
Do not confuse onunload with onbeforeunload: unload is not cancelable, and return false neither stops navigation nor displays a leave-page prompt. The example deliberately dispatches a synthetic event to demonstrate the attribute's connection to Window without closing the page; it does not reproduce actual document unloading.
Examples
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>onunload demonstration</title>
<body onunload="document.getElementById('result').textContent = event.type">
<output id="result">pending</output>
<script>
window.dispatchEvent(new Event('unload'));
window.onunload = null;
</script>
</body>
</html>Result
unload
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.