Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Page lifecycle events: visibility, leaving, and returning

Tell a hidden tab from an attempted departure or a back/forward cache restore, so you can save state, warn about unsaved edits, and resume work at the right time.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

document.addEventListener('visibilitychange', onVisibilityChange); // Read document.visibilityState or document.hidden.
window.addEventListener('beforeunload', onBeforeUnload); // Register only while unsaved changes exist.
window.removeEventListener('beforeunload', onBeforeUnload); // Remove the same listener once changes are saved or discarded.
window.addEventListener('pagehide', onPageHide); // Read event.persisted.
window.addEventListener('pageshow', onPageShow); // Read event.persisted.

The visibilitychange/beforeunload/pagehide/pageshow events are web platform APIs, not part of ECMAScript 2024. Support and behavior vary by browser and situation; don't assume all four events will fire in a fixed sequence.

Listen for visibilitychange on document. This event is not cancelable. Read document.visibilityState (visible or hidden) or the boolean document.hidden. Switching tabs can hide a page without leaving it. Save state as work progresses and treat the transition to hidden as your best final checkpoint or cue to pause work, not as proof that the session has ended.

beforeunload on window is a cancelable BeforeUnloadEvent associated with attempts to leave, reload, or close the page. To request confirmation, call event.preventDefault() and set event.returnValue to a nonempty string for legacy compatibility. Returning a value from the handler only works through onbeforeunload, not addEventListener(). The dialog requires prior qualifying user interaction (sticky activation); the browser may suppress it and controls its text. Register the listener only while edits are unsaved and remove it when they are saved or discarded: a listener can prevent bfcache use, including in Firefox.

pagehide and pageshow are non-cancelable PageTransitionEvents on window. On departure, pagehide with event.persisted === true means the browser intends to retain the document in memory for back/forward navigation (bfcache), not that it will be restored. false means no such intent. Use pagehide to pause resources, not to save critical data: both it and beforeunload may be skipped, for example when a mobile OS terminates a backgrounded browser.

On initial load, pageshow follows load and has persisted === false. A value of true means the same document was actually restored from bfcache: resume paused work and refresh data that may be stale. pageshow does not mean the user can see the page; it can fire in a background tab.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Page lifecycle events</title>
</head>
<body>
  <label><input id="dirty" type="checkbox" autocomplete="off"> Simulate unsaved changes</label>
  <script>
    const dirty = document.getElementById('dirty');

    function warn(event) {
      console.log('beforeunload');
      event.preventDefault();
      event.returnValue = 'unsaved'; // Legacy compatibility, not dialog text.
    }

    dirty.addEventListener('change', () => {
      if (dirty.checked) {
        window.addEventListener('beforeunload', warn);
      } else {
        window.removeEventListener('beforeunload', warn);
      }
    });

    document.addEventListener('visibilitychange', () => {
      console.log(`visibilitychange: ${document.visibilityState}`);
    });
    for (const type of ['pagehide', 'pageshow']) {
      window.addEventListener(type, (event) => {
        console.log(`${type}: persisted=${event.persisted}`);
      });
    }
    console.log('ready');
  </script>
</body>
</html>

Result

ready

Then, for example, after switching away from the tab and back:
visibilitychange: hidden
visibilitychange: visible

Other lines (not guaranteed and not in a fixed cross-event order):
beforeunload
pagehide: persisted=true
pageshow: persisted=true

A dispatched page transition event can also report persisted=false.

Open the example as an HTML page in a browser and check the console. `ready` appears immediately; later logs depend on your actions and the browser. The checkbox simulates unsaved changes but does not save anything.

Related lessons

  • JavaScript · Lesson 35 · Advanced · Version: 4

Sources