Service worker and messaging

Add the extension service worker

Register a background service worker for browser events without assuming it remains alive or keeps global state.

8 minute lesson

~~~

Manifest V3 uses an extension service worker for event-driven background behavior. The browser starts it when needed and can stop it when idle.

Declare the file under background.service_worker. Register event listeners synchronously at the top level so they exist when the worker starts. Persist important state in storage rather than global variables.

Think in independent events, not in one long-running process. Chrome normally terminates an idle extension worker after about 30 seconds, and it can end unexpectedly. The next command or message starts a fresh JavaScript instance where module globals have returned to their initial values. Do not add keep-alive work to fight that lifecycle.

{
  "background": {
    "service_worker": "service-worker.js",
    "type": "module"
  }
}

runtime.onInstalled is an extension lifecycle event used for installation and update initialization; it is not “the worker started.” runtime.onStartup refers to the browser profile starting and also does not fire for every worker wake. Put ordinary initialization in an idempotent function called by the event that needs it.

Listeners must be registered during initial module evaluation. Registering commands.onCommand only after awaiting a storage read creates a window where Chrome wakes the worker for a command but no listener is ready. Read required state inside the listener instead.

Store one counter only in a global and another in storage.session or storage.local. Invoke events, wait for the worker to stop, and invoke them again. Inspect the worker from chrome://extensions and explain the different results without relying on a startup log.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →