Extension Service Workers: Keeping State, Alarms and Messaging Without Losing Data
Why MV3 service workers stop, and the patterns that keep extensions reliable: top-level listeners, chrome.storage, alarms, messaging, offscreen documents and testing.
The most common Manifest V3 bug report sounds like this: “it works for a minute, then stops.” The cause is almost always the background service worker being shut down while the code expects it to stay alive. Chrome stops idle service workers on purpose, and extensions that are designed for that are fast and reliable. Extensions that fight it are fragile.
This guide explains the lifecycle and the patterns that work, based on Chrome’s documentation as of November 2026.
How the lifecycle works
Per Chrome’s service worker lifecycle docs:
- Chrome starts your service worker when an event it listens for fires: a message, an alarm, a tab update, a click on the action and so on.
- It normally terminates it after 30 seconds of inactivity. Receiving an event or calling an extension API resets that timer.
- A single event or API call that takes longer than 5 minutes can also cause termination.
When the worker stops, all in-memory state is gone: global variables, timers, open connections. The next event starts a fresh copy of your script from the top.
Pattern 1: register listeners at the top level
Chrome needs to know which events to wake you for. Listeners must be registered synchronously, at the top level of the script, every time it starts:
// ✅ Good: registered on every start
chrome.runtime.onMessage.addListener(handleMessage);
chrome.alarms.onAlarm.addListener(handleAlarm);
// ❌ Bad: registered only after an async step, so events that woke the worker can be missed
chrome.storage.local.get('enabled').then(({ enabled }) => {
if (enabled) chrome.tabs.onUpdated.addListener(onTabUpdated);
});
If a listener should only act sometimes, register it always and check the condition inside it.
Pattern 2: keep state in storage, not globals
// ❌ Lost when the worker stops
let counter = 0;
// ✅ Survives restarts
async function increment() {
const { counter = 0 } = await chrome.storage.local.get('counter');
await chrome.storage.local.set({ counter: counter + 1 });
}
Choose the right area:
| Storage area | Lifetime | Use for |
|---|---|---|
storage.session |
Until the browser closes; kept in memory | Temporary state, caches, tokens you don’t want on disk |
storage.local |
Until the extension is removed | Data and larger state |
storage.sync |
Synced through the user’s account; small quotas | User settings |
storage.session isn’t exposed to content scripts by default. Call setAccessLevel() if you need that. A small in-memory cache in front of storage is fine, as long as you treat it as disposable and reload from storage when it’s empty.
Pattern 3: use alarms, not setInterval
setTimeout and setInterval die with the worker. For anything scheduled, use chrome.alarms (needs the alarms permission, which shows no install warning):
chrome.runtime.onInstalled.addListener(() => {
chrome.alarms.create('refresh', { periodInMinutes: 15 });
});
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === 'refresh') await refreshData();
});
Since Chrome 120, alarms can fire as often as every 30 seconds (periodInMinutes: 0.5). Alarms usually persist, but they can be cleared in some situations, such as a browser restart on some platforms. Check with chrome.alarms.get() on startup and recreate if missing:
chrome.runtime.onStartup.addListener(async () => {
if (!(await chrome.alarms.get('refresh'))) {
chrome.alarms.create('refresh', { periodInMinutes: 15 });
}
});
Pattern 4: messaging that survives restarts
One-off messages (runtime.sendMessage) are the simplest and most robust. Each one wakes the worker if needed:
// content script or popup
const reply = await chrome.runtime.sendMessage({ type: 'getStatus' });
// service worker
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.type === 'getStatus') {
getStatus().then(sendResponse);
return true; // keep the channel open for the async response
}
});
That return true is the classic gotcha: without it, sendResponse called after an await arrives too late.
Long-lived ports (runtime.connect) are useful for streaming updates to a popup or side panel. Each message on a port resets the idle timer. But don’t open a port just to keep the worker alive. Design for restarts instead.
Pattern 5: need the DOM? Use an offscreen document
Service workers have no document or window. If you need DOM APIs, such as parsing HTML with DOMParser, copying to the clipboard or playing audio, Chrome provides the offscreen API: a hidden extension page created for a declared reason.
await chrome.offscreen.createDocument({
url: 'offscreen.html',
reasons: ['DOM_PARSER'],
justification: 'Parse HTML fetched from the user-selected site',
});
Only one offscreen document can exist at a time, so check before creating it, and close it when you’re done. Firefox doesn’t have this API, because its event pages already have a DOM. See the cross-browser checklist.
Pattern 6: make long work resumable
For tasks that may take a while, like syncing many items or processing a queue:
- Split the work into small chunks.
- Save progress (
lastProcessedId) to storage after each chunk. - Use an alarm to continue if the worker was stopped mid-way.
This way, a termination costs at most one chunk of repeated work.
Testing the hard cases
You can’t trust code that has never seen a cold start. Ways to force one:
- Open
chrome://serviceworker-internals, find your extension, and click Stop. Then trigger an event and confirm everything still works. - On
chrome://extensions, click the service worker link on your extension’s card to open DevTools for it. Note that while DevTools is open, the worker is kept alive, so close it when testing idle behavior. - Test after a browser restart, after an extension update, and after the computer wakes from sleep.
Quick reference
- Listeners: top level, always.
- State:
chrome.storage, never globals alone. - Timers:
chrome.alarms, minimum 30 seconds. - Messages:
return truefor async responses. - DOM work: offscreen document in Chrome.
- Long tasks: chunked and resumable.
Follow these and your extension won’t care how often Chrome stops its service worker, and users will see an extension that just works.