Skip to content

Lesson 3 of 9 · 21m

Service Workers, Events, and Extension Lifecycle

MV3 background workers are ephemeral event processors. Design registration, state, alarms, and startup so termination is normal rather than fatal.

Manifest V2 background pages behaved like tiny always-on applications. Manifest V3 ended that fantasy. A background service worker starts when an event arrives, does a bounded amount of work, and may be killed when idle. If your architecture assumes it stays alive, the browser will eventually teach it otherwise in production.

Register listeners synchronously at top level

chrome.runtime.onInstalled.addListener(async ({ reason }) => {
  if (reason === "install") await seedDefaults();
  if (reason === "update") await migrateStoredState();
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  handleMessage(message, sender).then(sendResponse);
  return true; // keep the response channel open for async work
});

chrome.alarms.onAlarm.addListener(async alarm => {
  if (alarm.name === "sync-rules") await syncRules();
});

Listener registration must happen while the initial script evaluates. If you hide it behind a later promise or a user interaction, an event can wake the worker, find no listener, and vanish into a bug report that only reproduces after browser restart.

Treat memory as a cache, not state

let compiledRules = null;

async function getRules() {
  if (compiledRules) return compiledRules;
  const { ruleText } = await chrome.storage.local.get("ruleText");
  compiledRules = compileRules(ruleText ?? "");
  return compiledRules;
}

That cache is a performance optimization, not a source of truth. Persist durable state in chrome.storage, reconstruct it after worker startup, and version your persisted schema. The service worker is a process that the browser may restart dozens of times a day.

Use alarms for time, not setTimeout

setTimeout can die with the worker. chrome.alarms survives termination and re-wakes it:

await chrome.alarms.create("sync-rules", {
  delayInMinutes: 1,
  periodInMinutes: 30
});

Alarms are coarse, subject to browser throttling, and not a cron service. They are correct for periodic refresh, cleanup, and retry. They are wrong for animation timing or precise seconds-level scheduling.

Long-running work needs a boundary

A worker event should acknowledge quickly and finish bounded work. Chunk expensive scans, write checkpoints, and resume if terminated. If the browser exposes a more suitable primitive — offscreen documents for DOM parsing in Chromium, for example — isolate that capability rather than pretending the background worker is a general-purpose server.

Field notes

  • return true from onMessage is required for asynchronous sendResponse; missing it produces intermittent empty responses.
  • runtime.onStartup does not fire for every worker start — it means browser startup, not service-worker startup.
  • Open extension service-worker DevTools from the browser's extension management page; ordinary page DevTools cannot see it.
  • Never keep authentication tokens only in worker memory if losing them would strand the user mid-flow.

Was this lesson helpful?

Sign in to rate