Implementation of Background Service Worker in Browser Extension
In Manifest V3, background script became a service worker. This is not just renaming — the lifecycle model changed. Service worker can be terminated by browser at any moment when there are no active tasks, and this breaks patterns that worked in MV2 with persistent background page.
Registration in manifest
{
"manifest_version": 3,
"background": {
"service_worker": "background/sw.js",
"type": "module"
}
}
type: "module" allows using ES-modules and import inside service worker. Supported in Chrome 93+.
Lifecycle: what really happens
Browser starts service worker on:
- extension install/update
- message from content script or popup
- alarm trigger (chrome.alarms)
- network event (if subscribed)
After all handlers complete, browser may kill process after ~30 seconds of inactivity. Next event will raise it again — with clean state.
This means: no global state in memory. Variables don't survive restart.
// BAD — state lost on SW restart
let requestCount = 0;
chrome.runtime.onMessage.addListener(() => {
requestCount++; // reset to 0 after restart
});
// GOOD — save in chrome.storage
chrome.runtime.onMessage.addListener(async () => {
const { requestCount = 0 } = await chrome.storage.local.get('requestCount');
await chrome.storage.local.set({ requestCount: requestCount + 1 });
});
Event handling: sync registration required
Event handlers must be registered synchronously at top level. If you register them inside async function or after await — browser may not "see" them when starting SW to handle event:
// background/sw.js
// CORRECT — sync registration at top level
chrome.runtime.onInstalled.addListener(onInstalled);
chrome.runtime.onMessage.addListener(onMessage);
chrome.alarms.onAlarm.addListener(onAlarm);
// Implementations can be async
async function onInstalled(details) {
if (details.reason === 'install') {
await chrome.storage.sync.set({ settings: defaultSettings });
}
}
function onMessage(message, sender, sendResponse) {
handleMessage(message, sender).then(sendResponse);
return true; // must return true for async responses
}
Long-lived connections via Port
For tasks that take more than few seconds (streaming, polling), use chrome.runtime.connect(). Active connection keeps SW alive:
chrome.runtime.onConnect.addListener((port) => {
if (port.name === 'long-running-task') {
handleLongRunningTask(port);
}
});
Timeline
Simple event handlers: 1–2 days. Complex with alarms, sync, long-running tasks: 3–5 days.







