Browser Engineering

bfcache with WebRTC: Avoiding Duplicate Connections on Return

Use pageshow.persisted and pagehide to pause connections, unregister listeners, reconcile on return, and opt out only when restoration cannot be made safe.

A sound implementation does not ask users to refresh until it works. Each phase has an input, an output, a timeout, and a terminal state. The back-forward cache restores an in-memory page without a normal reload. Network objects may be stale while old listeners remain; rerunning mount initialization creates duplicates.

Browser capability depends on version, permission, visibility, and device policy. Use capability detection and an explained fallback instead of treating one development machine as the product contract.

Define the system contract first

This capability crosses clients, networks, and servers, so a local optimization can create a system failure. Decisions must constrain both endpoints, persisted truth, and operating budgets together.

  • Record a page epoch and pause tasks on pagehide without deleting trust when persisted is true.
  • On pageshow, inspect old object state before reuse, ICE restart, or full replacement.
  • Bind global and channel callbacks to a page epoch so stale events cannot mutate current stores.

Safe bfcache support needs page epochs and idempotent initialization: reconcile reusable objects and explicitly replace the rest.

What can break that contract

Production failures often appear when two individually valid actions overlap. Inspect stale messages, duplicate effects, exhausted resources, and mixed versions instead of patching only the current stack frame.

  • A permanent beforeunload listener disqualifies the page from bfcache and slows navigation.
  • Return always calls connect while the old WebSocket is alive, duplicating notifications and messages.
  • Avoiding all leave signaling for cache makes the remote believe a viewer remains indefinitely.

How to test the contract line by line

A release gate combines deterministic regression, randomized timing, and real browser pairs. Preserve the seed and state trace from every failure as a permanent replay case.

  1. Navigate back and forward one hundred times and assert one signaling connection and one handler.
  2. While cached, keep, fail, or replace the old connection and verify the return decision.
  3. Enter bfcache during viewing and receiving; remote state must converge after its grace period.

The release standard is practical: the normal path is fast, abnormal paths converge, recovery never overrides an explicit user decision, and operators can diagnose faults from limited, privacy-safe evidence.

Put the guide to work

Open uCopy and connect two devices securely from the browser.

Start for free