DEV Community

Cover image for Use `pagehide` and `persisted` to separate pause from cleanup
Chris Rodriguez
Chris Rodriguez

Posted on Originally published at chriseugenerodriguez.com

Use `pagehide` and `persisted` to separate pause from cleanup

A page hidden during history navigation is not necessarily gone. The browser may keep it in the back/forward cache (bfcache) and restore it later. That makes a blanket pagehide cleanup handler risky: it can erase state that the restored page was meant to retain.

The implementation should make one explicit decision from the event supplied by the browser. Register a window-level pagehide listener and inspect event.persisted. When it is true, the browser intends to cache the page. Pause work that should stop while the page is hidden and keep the state needed if it returns. For example, stop a timer or temporary activity while retaining an unfinished draft. When the flag is false—or absent—take the cleanup path and release state that must not survive a non-restorable transition.

The inserted example keeps those responsibilities separate through two callbacks. The persisted branch pauses and returns immediately, so cleanup cannot accidentally run afterward. The other branch performs irreversible teardown. It also returns an uninstaller, which matters when a component or page integration can mount lifecycle behavior more than once.

Expected behavior is intentionally narrow. A persisted synthetic event results in paused work while the resumable draft remains available. A non-persisted event results in cleanup and removes that draft. An event without the flag follows the conservative cleanup path.

That test boundary is important. A recording window-like dependency can prove that the application reacts correctly to each event shape; it does not reproduce browser navigation or prove bfcache eligibility in a real engine. The browser decides whether a page is cached, and that decision varies with browser behavior and page features.

This pattern is for history-navigation lifecycle policy, not universal shutdown handling. pagehide is not guaranteed in every mobile termination scenario, and end-of-session analytics has different lifecycle requirements. Use this branch only after identifying which state is resumable and which resources must be released.

Working example

/**
 * 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);
    }
  };
}
Enter fullscreen mode Exit fullscreen mode

Read the full article: https://chriseugenerodriguez.com/blog/pagehide-persisted-cleanup

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

Chris, the detail that does the most work here is the early return in the persisted branch — pause() runs and the function exits before cleanup can touch the draft. That one line is the whole post, because a blanket pagehide handler is exactly how drafts get wiped on back-navigation.

The half I kept waiting for is the resume. Pause without a pageshow mirror leaves a restored page frozen: the timer you stopped never restarts, the polling you paused never resumes, and the draft is intact but the page is half-dead. Your installPagehideLifecycle returns an uninstaller for double-mounting, which is the right instinct — but where does resume live in your design? Is pause() expected to re-arm itself on a pageshow listener with persisted === true, or does the caller wire that second listener separately?

One more edge worth naming: the non-persisted cleanup path is also where people sneak in their analytics flush, and pagehide is not guaranteed on mobile termination — so a flush that only lives in cleanup silently loses the sessions that need it most. Do you treat sendBeacon as part of cleanup, or keep it on a separate path entirely?