CKTIS / HTML
onpopstate — handling changes to the active history entry
The onpopstate attribute on body sets the Window object's popstate event handler. It lets a page respond to session history traversal, such as Back and Forward navigation, and read the destination entry's state.
Version: WHATWG HTML Living Standard; index snapshot date recorded separately
Syntax
<body onpopstate="handleState(event)">
window.onpopstate = handleState;onpopstate is an event handler attribute available on body, not a global attribute for arbitrary elements. It exposes the Window object's popstate handler. Assigning window.onpopstate = handleState sets that same handler; it does not create a second, independent listener.
popstate is associated with session history traversal, for example through Back, Forward, or history.back(). Calling history.pushState() or history.replaceState() alone does not fire it. Inside the handler, event.state contains the restored state of the destination entry; it can be null, so account for that before accessing its properties.
A subsequent assignment to window.onpopstate replaces the previous handler, and assigning null removes it. For independent handlers, use window.addEventListener('popstate', handleState). Do not treat popstate as an opportunity to cancel navigation.
The example deliberately dispatches a synthetic PopStateEvent with fixed state. It checks the attribute's connection to Window, but neither changes history nor tests actual history traversal. An application's CSP can block inline handler attributes; in that case, register the handler in a permitted script.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>onpopstate demo</title>
</head>
<body onpopstate="document.getElementById('result').textContent = 'step=' + event.state.step">
<button id="test" type="button">Test</button>
<output id="result">Ready</output>
<script>
document.getElementById('test').addEventListener('click', () => {
window.dispatchEvent(new PopStateEvent('popstate', {
state: { step: 1 }
}));
});
</script>
</body>
</html>Result
step=1
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.