IHOR.DEVKNOWLEDGE_BASE
MENU

~/blog / Extensions / chrome-extension-service-workers-explained.md

// pillar guide · 4 min read

Chrome Extension Service Workers Explained

Understand Manifest V3 worker startup, listener registration, idle termination, storage ownership, and a restart-safe badge example without keepalive tricks.

Quick answer

A Manifest V3 service worker is an event handler that Chrome starts when needed and may terminate when idle. It has no page DOM and its global variables disappear when its process ends. Register event listeners synchronously at module evaluation, load persistent data inside handlers, and make operations safe to repeat.

The worker is useful for installation events, commands, alarms, and coordination that belongs outside an open popup. It is not a permanent server for UI state. A popup can use storage directly, and a content script should own its interaction with a particular document. Keeping every operation in the worker adds messaging without making document state durable.

Practical implementation steps

Register before asynchronous initialization

If listener registration happens after awaiting a settings fetch, the event that woke the worker can arrive before its handler exists. Register first. Then let each handler await an initialization promise or read the data it needs. Static imports are supported for a module worker; dynamic import() is not supported there.

Separate cache from source of truth

A module-level cache can reduce repeated reads during one worker lifetime, but correctness must survive an empty cache. Use storage.local for persistent records or storage.session for suitable browser-session data. Do not rely on localStorage: the worker lacks that window API.

Design around interruption

Chrome’s lifecycle documentation describes idle and long-task limits, with changes across browser versions. Those limits explain why short handlers and saved progress matter; they are not an exact scheduling promise to build a workflow around. A network request can fail or a browser can close before completion. Save a pending operation identifier before an important external side effect and reconcile it when the worker resumes.

Test the cold path

Close the worker’s DevTools before evaluating idle behavior because inspection changes its lifetime. Trigger the feature after inactivity or a browser restart and verify that it reconstructs state. A warm-worker success does not establish restart safety. LocaleStress’s saved reports illustrate a record that should remain available independently of any background process; that is a product requirement rather than a claim about its internals.

Implementation example

With storage permission and a declared action, this worker derives a badge from stored data whenever that data changes and whenever the worker starts. No counter is kept only in memory.

async function refreshBadge() {
  const { savedCount = 0 } = await chrome.storage.local.get("savedCount");
  const count = Number.isInteger(savedCount) && savedCount >= 0 ? savedCount : 0;
  await chrome.action.setBadgeText({ text: count ? String(count) : "" });
}

chrome.storage.onChanged.addListener((changes, area) => {
  if (area === "local" && "savedCount" in changes) {
    void refreshBadge().catch(console.error);
  }
});

chrome.runtime.onInstalled.addListener(() => {
  void refreshBadge().catch(console.error);
});

void refreshBadge().catch(console.error);

This is a derived-display example, not a transactional counter implementation. If several callers modify savedCount, a read-then-increment sequence can lose updates. Assign writes to one owner or store individually identified records and derive the count. Repeated badge writes are harmless, making reconstruction a simpler choice than persisting a second badge state.

Tradeoffs and alternatives

Use alarms for work that should be revisited later, while accepting that delivery can be delayed. Use an extension page for a user-visible task that needs a DOM. An offscreen document is a specialized capability with its own reasons and restrictions, not a general replacement for the old persistent background page.

A port supports repeated messaging, but opening one is not a universal worker keepalive strategy. Lifecycle behavior is version-sensitive; choose a documented minimum browser version when relying on a specific change. Prefer short, resumable operations over artificial periodic activity.

Common mistakes

  • Registering listeners only after a network or storage promise resolves.
  • Treating module globals or setInterval as durable state or a reliable scheduler.
  • Reading DOM APIs from worker imports.
  • Verifying idle behavior with worker DevTools left open.
  • Overwriting saved preferences on every update instead of migrating only missing fields.

Production checklist

  • Listener registration happens during module evaluation.
  • Every important operation works with empty module globals.
  • Storage errors and rejected promises are observed.
  • External side effects have an interruption/retry policy.
  • Cold-start checks run with worker inspection closed.
  • API-version assumptions are recorded beside the minimum browser version.

FAQ

Does the worker survive a popup closing?

The worker has a separate lifetime, but that does not guarantee arbitrary work will finish. Persist meaningful progress and expose a way to recover.

Should every storage call go through the worker?

Only when centralized authorization or write ownership needs it. Extension pages can use storage directly.

What should I change first in an unreliable worker?

Move listeners to the top level, remove correctness dependencies on globals, and reproduce the operation from a cold start. Those changes target lifecycle failure before adding a new state-management library.

Primary sources

Ihor Kharchyshyn

Independent full-stack product engineer writing source-backed implementation guides for browser extensions and modern web products.

Need this implemented in a real product?

Browser tools with a clear purpose, focused permissions, and a maintainable Manifest V3 architecture.