Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Extension Background Events and Durable State

Last updated: 5 Oct 20268 min read
tutorial
IntermediateBy AITrove Editorial

An extension’s background event handler may be loaded when an event arrives and stopped when idle. In-memory variables are therefore a cache, not a durable queue or source of truth. A popup can close before its request finishes, and a content script can disappear when the tab navigates. A long operation needs a stable ID, persisted state, and an explicit owner for retries. Event listeners should be registered where the runtime can find them after restart. A background timer alone is a poor durability guarantee for an important user task.

Working case

A reviewer selects case 47 and asks the helper to save a checklist. The popup closes as soon as the user clicks outside it; the background handler begins a server call, then the browser suspends it. A naive global variable held the request state, so the next click sends another checklist and the reviewer sees two copies. The revised flow creates operation 63 with a scoped idempotency key, stores pending metadata in extension storage, and lets the server own the authoritative completion state. When the handler wakes again, it reloads the operation ID and reconciles with the server before retrying. A completed operation is shown once in the popup.

Implementation boundary

javascript
function shouldRetryChecklist(local, server) {
  return local.key === server.key && server.state === 'not-found' &&
    local.attempts < 3 && local.sessionCurrent;
}
console.log(shouldRetryChecklist({ key: 'review-63', attempts: 1, sessionCurrent: true }, { key: 'review-63', state: 'completed' }));
// Output: false

Keep background handlers short and event-driven. Persist only the minimum operation metadata needed to recover; private case notes should stay on the authorized server or use an explicit local retention rule. Register listeners at module initialization so a new worker can receive events. Tie a popup command to a server operation key and wait for an acknowledgement that identifies durable admission. When a network call fails ambiguously, query status before deciding whether to retry. Distinguish queued, sending, completed, failed, and canceled states. Do not promise that an alarm, port, or open popup will keep a worker alive indefinitely. Recheck user session and case access before replaying after browser restart. Remove or expire old pending records so storage does not grow without bound.

Cost and boundaries

A storage read per event and an indexed status lookup add small latency; they prevent duplicate server effects and lost user state. Stored pending operations take O(P) space for P unfinished tasks until expiry. Polling too often from every popup can create unnecessary server load, so use bounded refresh and pause when hidden. A restart can cause several pending tasks to wake together; limit concurrency and backoff. Measure pending age, duplicate admission, completion after restart, storage size, and user-visible unknown outcomes. Avoid treating a local completed flag as stronger evidence than the server’s operation record.

Failure trace

Close the popup immediately after submission and reopen it; the status should still be recoverable. Stop the background handler after server admission but before its response arrives, then retry with the same key and require one checklist. Restart the browser with an operation pending, revoke case permission, and deny replay or result access. Let local storage write fail and show an honest uncertain state rather than claiming success. Trigger the same event twice and confirm one effect. Expire a pending record only after its retry window and reconciliation policy. Inspect whether private note text remains in extension storage after sign-out.

Verification

  • Popup closure cannot lose the operation identity.
  • Ambiguous network failure does not create a duplicate.
  • Restart replay rechecks current session and case access.

Practice drill

Save a checklist for case 47 with operation key review-63. Simulate a popup close at 20 milliseconds and background suspension after the server commits. Reopen the helper, reload pending metadata, and reconcile operation 63. Repeat after account sign-out and browser restart. Record every server operation ID and local state transition. Then create 83 pending tasks and verify bounded status refresh, storage cleanup, and no duplicate checklist rows.

Decision note

Extension memory can vanish between events; durable state and idempotent server operations carry the workflow.

Common Mistakes

  • Holding important state only in a global variable.
  • Retrying a server write with a new key.
  • Assuming an event handler stays alive until work completes.

Related lessons

Browser Extension Trust and Lifecycle; Extension Host Permissions and User Invocation; Content Script Isolation and DOM Mutation; Extension Message Contracts and Page Data Boundary; Background Workflow Reliability; Idempotent Write Requests and Lost Responses.

Connected practice

Build Project: permit checklist browser helper and review Web Development: extension boundary decisions quiz.

web-tech
web-development
Storage details