Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onpagehide — handling page departure

The onpagehide attribute on body registers a handler for the Window object's pagehide event. In a browser-generated event, event.persisted set to true indicates an intent to retain the document for possible reuse, not that it is actually retained.

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

Syntax

<body onpagehide="JavaScript statements">

onpagehide is an event handler attribute for pagehide. When placed on body, it handles the event on Window, not an event limited to that element. It is not a global attribute available on arbitrary elements. The standard also exposes it on the legacy frameset element. Its value contains JavaScript statements; the event object is available as event.

The pagehide event concerns leaving a page, not merely switching tabs. In a browser-generated event, the PageTransitionEvent object's persisted property is false when the document is being left for the last time and true when the browser intends to retain it for possible reuse, such as in the back/forward cache (bfcache). A value of true guarantees neither actual retention nor later restoration.

The JavaScript counterpart is window.onpagehide = handler; assignment replaces the previous handler in that property. window.addEventListener('pagehide', handler) lets you register independent listeners. The example dispatches a synthetic event for repeatable output: it neither leaves the page nor places it in bfcache.

Examples

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>onpagehide demo</title>
<body onpagehide="document.getElementById('result').textContent = event.type + ': persisted=' + event.persisted">
  <output id="result">Waiting</output>
  <script>
    window.dispatchEvent(new PageTransitionEvent('pagehide', {
      persisted: true
    }));
  </script>
</body>
</html>

Result

pagehide: persisted=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