pageshow Detects Back-Forward Cache Restores

pageshow fires on every load and on back-forward cache restores; persisted means timers and sockets were frozen, so live subscriptions must be re-established.

TypescriptResilience

Code

typescriptsnippet
20 lines
function refreshLiveRegion(): void {
  console.log('repainting live quotes at', new Date().toISOString());
}

// pagehide with persisted === true means the page enters the
// back-forward cache instead of being destroyed.
window.addEventListener('pagehide', (event) => {
  console.log('entering back-forward cache:', event.persisted);
});

// pageshow fires on every load AND on bfcache restores; a persisted restore
// means timers and sockets were frozen and need to be re-established.
window.addEventListener('pageshow', (event) => {
  if (event.persisted) {
    refreshLiveRegion();
    console.log('restored from bfcache — resuming live updates');
  } else {
    console.log('fresh load — initial fetch');
  }
});

The code at a glance — pageshow Detects Back-Forward Cache Restores

pageshow Detects Back-Forward Cache Restores is built around the function refreshLiveRegion.

Watch out for

  • Nothing gets resolved or downloaded — the bare toolchain executes it.
  • window exist only in browsers — a Node runtime has no shims for them out of the box.

Applying it

Signature: function refreshLiveRegion()

The run prints repainting live quotes at, entering back-forward cache:, restored from bfcache — resuming live updates — each prefix names the step that produced it.

Statements that matter

window.addEventListener('pagehide', (event) => {
  console.log('entering back-forward cache:', event.persisted);
});
window.addEventListener('pageshow', (event) => {
  if (event.persisted) {
    refreshLiveRegion();
    console.log('restored from bfcache — resuming live updates');
  } else {
    console.log('fresh load — initial fetch');
  }
});

Interactive Tools for This Topic

FAQ

Does pageshow Detects Back-Forward Cache Restores run in plain Node.js?
No — it touches `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.