Use pagehide to pause or clean up
Use `pagehide` with `event.persisted` to pause resumable work for bfcache and clean up only when the page will not return.
When a browser hides the current page during history navigation, the page is not always disappearing forever. Sometimes it is moving into the back/forward cache, which means the browser may restore it later with its state intact. Other times the page is leaving for good, so anything that cannot be reconstructed has to be cleaned up before the page is discarded.
That difference is why a single `pagehide` listener is useful only when it branches on `PageTransitionEvent.persisted`. The supplied example keeps resumable state on the cached path and performs cleanup on the non-persisted path. The tests exercise both branches so the article can show the decision clearly without pretending that a synthetic fixture proves browser cache behavior itself.
Start with the two different exits
A page that disappears from the screen is not always gone for good. In browser history navigation, the current page can be hidden while the browser prepares another entry, and that hidden page may still be eligible to return from the back/forward cache. The practical consequence is that one lifecycle event can mean two very different things for your code.
That distinction matters when your page owns work with different lifetimes. Some work should merely stop while the page is out of view, because it can resume later. Other work should be torn down because it cannot safely survive a history round-trip. If you collapse those cases into one cleanup path, a cached page comes back missing state it was supposed to keep.
The tested example treats that split as the main design decision. `pause()` preserves resumable state such as an unfinished draft, while `cleanup()` discards state that should not survive a non-restorable navigation. The rest of the article is about choosing the right branch, not about inventing extra lifecycle machinery.
- The page may be hidden because the browser is leaving it in the back/forward cache.
- `event.persisted` is the branch that tells you whether that hidden page can return later.
- Pause temporary work on the cached path; reserve irreversible cleanup for the discard path.
/**
* Installs the pagehide branch used by a browser page.
*
* This unit-testable function proves only the application's branching behavior.
* A real browser must supply the PageTransitionEvent during navigation.
*/
export function installPagehideLifecycle(windowLike, work) {
if (!windowLike || typeof windowLike.addEventListener !== "function") {
throw new TypeError("windowLike must provide addEventListener");
}
const { pause, cleanup } = work ?? {};
if (typeof pause !== "function" || typeof cleanup !== "function") {
throw new TypeError("pause and cleanup must be functions");
}
function onPageHide(event) {
// A persisted page may be restored from the back/forward cache, so retain
// resumable state while stopping work that should not continue while hidden.
if (event?.persisted === true) {
pause.call(work);
return;
}
// Without persistence, the page will not be restored from this transition.
cleanup.call(work);
}
windowLike.addEventListener("pagehide", onPageHide);
return () => {
if (typeof windowLike.removeEventListener === "function") {
windowLike.removeEventListener("pagehide", onPageHide);
}
};
}
SourcesMDN: Window pagehide event (opens a new tab)MDN: PageTransitionEvent.persisted (opens a new tab)
Why `pagehide` and `persisted` belong together
MDN describes `pagehide` as the event fired when the browser hides the current page during session-history navigation. That description is broad enough to include both a page that will be revisited and a page that will be discarded. The event name alone does not tell you which outcome is happening, which is why `pagehide` by itself is not enough to choose the right behavior.
The branch comes from `PageTransitionEvent.persisted`. When that read-only flag is true, the browser is indicating that the page is being loaded from cache. In other words, the page is not being destroyed in the ordinary sense; it is entering a suspended state that may later be restored. That is the signal the application needs before deciding whether to keep resumable state around.
The example uses that contract directly. It does not infer persistence from user-agent strings or from a guessed navigation pattern. It reacts to the event object the browser provides, which keeps the decision tied to the browser’s own lifecycle model instead of to an application guess.
- `pagehide` is the event to watch at the window level.
- The event object is a `PageTransitionEvent`, so the branch lives on `event.persisted`.
- A real browser decides whether the page is being cached; your code reacts to that decision.
SourcesMDN: Window pagehide event (opens a new tab)MDN: PageTransitionEvent.persisted (opens a new tab)
The handler is small because the contract is small
The implementation is intentionally narrow. It installs one `pagehide` listener and branches only on `event.persisted`. If the event says the page is persisted, the code calls `pause()` and returns. Otherwise it calls `cleanup()`. That is enough because the browser already owns the hard part: deciding whether the page can reappear from cache.
The important part is what each branch means. `pause()` stands for stopping temporary activity without discarding the state you want to resume later. In the article’s fixture, that state is a draft string. `cleanup()` stands for irreversible teardown, and the example makes that concrete by setting the draft to `undefined`. The branches are not symmetrical, because the costs of a wrong choice are not symmetrical either.
The listener also gives you a clean uninstallation path by returning a remover function. That detail matters in real code that mounts and unmounts the lifecycle behavior more than once. The handler itself is the core of the article; the teardown function just keeps the integration honest.
- The listener pauses work when `event.persisted === true`.
- The same listener cleans up when persistence is false or absent.
- The conservative branch is the safer default for non-cached exits.
What the example proves and what it leaves open
The provided Node test fixture proves the application-owned branching behavior, not the browser’s navigation engine. It dispatches a synthetic `pagehide` event into a small window-like object and checks the resulting work state. That makes the policy visible: persisted events pause and retain the draft, while non-persisted events clean up and clear it.
That proof boundary is useful because it separates the decision from the environment. A test that only says “the listener exists” would miss the point. A test that only says “cleanup ran” would not tell you whether the cached-page path was preserved. Here the success condition is the branch outcome, not just event registration or object mutation.
What the fixture does not prove is how a specific browser decides cache eligibility on a real history traversal. MDN’s compatibility notes and lifecycle guidance explain the browser-facing contract, but the actual cache behavior still depends on the browser and on the page’s own features. This article therefore treats the browser decision as external and verifies only the code that consumes it.
- Persisted history navigation should retain resumable state.
- Non-persisted navigation should drop state that cannot safely survive a return.
- A branch that always cleans up is correct for one path and wrong for the other.
SourcesMDN: PageTransitionEvent.persisted (opens a new tab)MDN: Window pagehide event (opens a new tab)
Limits and applicability
This pattern fits pages that have two kinds of state: state that can resume and state that must be rebuilt. Draft text, UI draft selections, in-memory caches, and transient timers are common examples. If your page does not keep anything worth preserving, the branch may be unnecessary. If your state is already externalized somewhere durable, the pause path may be only a minor optimization.
The pattern does not mean every hidden page should be kept alive indefinitely. MDN explicitly notes that `pagehide` is not reliably fired in every mobile situation, and that `visibilitychange` is the better signal for end-of-session style tracking. Those are different questions. This article is about choosing between resumable suspension and cleanup during history navigation, not about session analytics or universal page shutdown handling.
The incomplete fix is to always clean up because cleanup feels safer. That approach avoids leaks, but it also destroys state that a cached page could have reused. The other incomplete fix is to always pause because reuse sounds efficient. That leaves non-resumable state hanging around when the page will not come back. The branch is the whole point, and the branch has to match the browser’s persistence signal.
- Treat `pagehide` as a lifecycle signal, not as proof that the session ended.
- Use the conservative path for non-persisted exits when state cannot be reconstructed cheaply.
- Keep the distinction between temporary suspension and teardown visible in code and tests.
SourcesMDN: Window pagehide event (opens a new tab)MDN: PageTransitionEvent.persisted (opens a new tab)
The ownership question behind the branch
The deeper question is not “which event should I listen to?” but “which piece of state does the page own, and for how long?” `pagehide` gives you the moment when the browser is transitioning away. `persisted` tells you whether that transition is temporary enough that the page may return. The code then decides what must survive and what must be released.
That framing helps when you have more than one kind of temporary work. A typing draft can be paused and resumed. A WebSocket or active subscription may need cleanup because the browser will not keep that connection alive simply because the page can be cached. In practice, a page often needs both behaviors at once: preserve what is resumable, and release what is not.
The article’s example uses a single draft string to keep the contract readable, but the same ownership rule scales to larger components. The point is not to make every pagehide handler identical. The point is to make the distinction explicit enough that the next person reading the code can tell why the page pauses in one branch and tears down in the other.
- A persisted page should behave like a suspended page, not a brand-new one.
- A discarded page should finish its cleanup before the browser forgets it.
- The right mental model is ownership of state, not ownership of the event.
import test from "node:test";
import assert from "node:assert/strict";
import { installPagehideLifecycle } from "./main.mjs";
function createWindowLike() {
const listeners = new Map();
return {
addEventListener(name, listener) {
listeners.set(name, listener);
},
removeEventListener(name, listener) {
if (listeners.get(name) === listener) listeners.delete(name);
},
dispatchPagehide(event) {
listeners.get("pagehide")?.(event);
},
};
}
function createWork() {
return {
resumableDraft: "unfinished message",
paused: false,
cleaned: false,
pause() {
this.paused = true;
},
cleanup() {
this.cleaned = true;
this.resumableDraft = undefined;
},
};
}
test("persisted pagehide pauses work and retains resumable state for a history restoration", () => {
const windowLike = createWindowLike();
const work = createWork();
installPagehideLifecycle(windowLike, work);
windowLike.dispatchPagehide({ persisted: true });
assert.equal(work.paused, true);
assert.equal(work.cleaned, false);
assert.equal(work.resumableDraft, "unfinished message");
});
test("non-persisted pagehide runs cleanup and discards non-resumable state", () => {
const windowLike = createWindowLike();
const work = createWork();
installPagehideLifecycle(windowLike, work);
windowLike.dispatchPagehide({ persisted: false });
assert.equal(work.paused, false);
assert.equal(work.cleaned, true);
assert.equal(work.resumableDraft, undefined);
});
test("a pagehide event without persisted follows the conservative cleanup path", () => {
const windowLike = createWindowLike();
const work = createWork();
installPagehideLifecycle(windowLike, work);
windowLike.dispatchPagehide({});
assert.equal(work.paused, false);
assert.equal(work.cleaned, true);
assert.equal(work.resumableDraft, undefined);
});
SourcesMDN: Window pagehide event (opens a new tab)MDN: PageTransitionEvent.persisted (opens a new tab)


