Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 36 ยท Background Service Workers

Service Worker Basics

Learn the extension service worker: declare it in the manifest, register listeners at the top level, use chrome.runtime.onInstalled, avoid DOM and global state, and import modules.

The service worker is the background brain of a Manifest V3 extension. It has no window and no page, so nothing is ever shown. Instead it sits quietly and reacts to events: the extension was installed, the user pressed a shortcut, a tab finished loading, an alarm rang, a message arrived from a popup or content script. When there is nothing to do, Chrome stops it to save memory.

If you came from Manifest V2, the service worker replaces the background page. The big difference is that it does not stay alive, and that shapes how you write it.

Declare it

JSON
"background": {
  "service_worker": "background.js",
  "type": "module"
}

type: "module" is optional. It lets you use import and export inside the worker. Without it, you can use importScripts("helper.js") with local files.

The worker is one file at the root of your declaration. It cannot be an HTML page, and it has no window or document. It has self, fetch, setTimeout, indexedDB, caches, OffscreenCanvas and the chrome.* APIs you have permission for. No localStorage, no DOM, no XMLHttpRequest.

Your first service worker

JavaScript
// background.js
chrome.runtime.onInstalled.addListener((details) => {
  console.log("Installed or updated:", details.reason);

  if (details.reason === "install") {
    chrome.storage.local.set({ installedAt: Date.now(), count: 0 });
  }
});

chrome.action.onClicked.addListener(async (tab) => {
  const { count } = await chrome.storage.local.get({ count: 0 });
  await chrome.storage.local.set({ count: count + 1 });
  chrome.action.setBadgeText({ text: String(count + 1), tabId: tab.id });
});

details.reason is "install", "update" or "chrome_update". onInstalled is where you set default data, create context-menu items and show a welcome page. It runs once per install or update, not on every browser start.

Rule 1: register listeners at the top level

Chrome wakes the service worker, runs the script from the top, and then delivers the event to listeners that were registered during that first synchronous run. If you add a listener later (inside an await, a setTimeout or another callback), the event arrives before it is registered and is lost.

JavaScript
// WRONG: registered after an await, so it may miss the event
const settings = await chrome.storage.local.get();
chrome.tabs.onUpdated.addListener(handler);

// RIGHT: register first, load data inside the handler
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo) => {
  const settings = await chrome.storage.local.get();
  // ...
});

Rule 2: no global state

Variables in the worker disappear when it stops. This code counts wrongly:

JavaScript
let clicks = 0;   // reset every time the worker restarts!
chrome.action.onClicked.addListener(() => { clicks++; });

Use chrome.storage.session (cleared when the browser closes, in memory only) for temporary data and chrome.storage.local for persistent data. A small cache in a variable is fine if you can rebuild it.

flowchart LR
    E["Event: click, alarm, message"] --> W["Chrome wakes the worker"]
    W --> R["Script runs top to bottom<br/>listeners registered"]
    R --> H["Matching listener handles event"]
    H --> I{"Idle for ~30 s?"}
    I -- yes --> S["Worker stopped<br/>variables lost"]
    I -- no --> H
    S -. next event .-> W

The worker starts fresh after every sleep.

Rule 3: no DOM, so no DOM tools

Things that need a document will fail: document.createElement, new Audio(), DOMParser, window.open, navigator.clipboard. For these Chrome offers the Offscreen Documents API: you ask for a hidden page that has a DOM, do the job there and message the result back. You will meet it in the events and alarms lesson.

Splitting code into modules

With "type": "module" your worker can import other files:

JavaScript
// background.js
import { track } from "./lib/analytics.js";
import { setupMenus } from "./lib/menus.js";

chrome.runtime.onInstalled.addListener(setupMenus);
chrome.action.onClicked.addListener(() => track("click"));

All imports run at start, so keep the module graph small. Listeners in imported modules must also register synchronously at the top level.

Simulating the lifecycle

You cannot run Chrome's real worker here, but a small simulator makes the lifecycle concrete: it "starts" a fresh scope each time, so state kept in a variable is lost while stored state survives.

JS State in a variable vs in storage

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The listener-timing mistake, reproduced

This shows why a listener added after an await can miss the event that woke the worker.

JS Why top-level registration matters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Debugging the worker

On chrome://extensions, the card of your extension has a service worker link. Click it to open DevTools attached to the worker: its console shows your console.log output and its Network tab shows requests. Opening DevTools keeps the worker alive, which can hide lifecycle bugs. To see real behavior, close DevTools and use the Application โ†’ Service workers tools, or watch for the "inactive" label on the card.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why must event listeners be registered synchronously at the top level?

    If you register after an await, the event may already be dispatched. Register first, load data inside the handler.
  2. 2. Where should a counter that must survive worker restarts live?

    Worker memory is lost when it stops; storage persists.
  3. 3. Which of these is NOT available in an extension service worker?

    The worker has no DOM. Use an offscreen document if you need one.

Summary

  • The MV3 service worker is event-driven, has no DOM and is stopped when idle.
  • Declare it with background.service_worker (add "type": "module" for imports).
  • Register all listeners synchronously at the top level.
  • Keep state in chrome.storage, not in variables.
  • Inspect it through the "service worker" link on chrome://extensions.

Next: The Service Worker Lifecycle