Skip to content
AnswerWell geo Documentation

Research · 9 min read · Answerwell

Extension Service Worker Lifecycle, Events, and Manifest Background

How Chrome extension service workers register in the manifest, handle events, shut down when idle, use offscreen documents, and migrate from background scripts.

This page summarises Chrome Extensions documentation on extension service workers: the Manifest V3 background script that acts as the extension’s central event handler. It differs from web service workers and from the deprecated Manifest V2 background script / event page model described in About extension service workers and Migrate to a service worker.

Extension service worker vs background script: what runs in the background

Section titled “Extension service worker vs background script: what runs in the background”

An extension service worker is the extension’s main event-based background script. Chrome loads it when needed and unloads it when it goes dormant.

Extension service workers are an extension’s central event handler. That makes them just different enough from web service workers that the mountains of service worker articles around the web may or may not be useful.

— Chrome, About extension service workers

Compared with a long-lived Manifest V2 background page, Manifest V3 moves background work to service workers that run only when needed:

Extensions in Manifest V2 had a long-lived background page that took up resources, even when an extension wasn’t running. In Manifest V3, we have moved the background context to service workers, which run only when needed.

— Chrome, What is Manifest V3?

Extension service workers share some behaviour with web service workers (no DOM access, load on demand), but they also handle extension API events—navigation, notifications, tab closure—and are registered via the manifest, not navigator.serviceWorker.register(). Chrome’s docs now prefer the term extension service worker over background script to avoid confusion with Manifest V2’s background.scripts feature (About extension service workers).

Aspect Web service worker Extension service worker
Registration serviceWorker.register() on a site background.service_worker in manifest background
DOM No No (use Offscreen API for DOM APIs)
Typical role Network/cache proxy Extension events + messaging + lifecycle
Updates Page-driven New extension package (no remote code) (Extension service worker basics)

Manifest background: how to register the service worker file

Section titled “Manifest background: how to register the service worker file”

To register an extension service worker, set the service_worker key under background in manifest.json. This replaces Manifest V2’s background.scripts array and persistent flag (Migrate to a service worker).

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

Use "type": "module" only when the worker uses ES import (Extension service worker basics). To split code across files, use import (with "type": "module") or importScripts(); dynamic import() is not supported in the worker.

Publishing a new Chrome Web Store version updates the worker; Manifest V3 does not allow remotely hosted executable code in the background context (Extension service worker basics).

After changing the manifest or service worker file, reload the extension; popups and options pages may refresh without a full extension reload (Hello World extension).

Extension service worker lifecycle: install, startup, idle, and shutdown

Section titled “Extension service worker lifecycle: install, startup, idle, and shutdown”

The extension service worker lifecycle chains standard service worker steps with extension runtime events.

Installation order when the extension is installed or updated

Section titled “Installation order when the extension is installed or updated”

When a user installs from the Chrome Web Store, loads an unpacked extension, or updates either, Chrome runs, in order:

  1. install (service worker event)
  2. browser.runtime.onInstalled (extension event)
  3. activate (service worker event)

Unlike web workers, activate runs right after install because there is no page reload in an extension (The extension service worker lifecycle).

When a profile that has the extension installed starts, browser.runtime.onStartup fires. No service worker lifecycle events are invoked for that case (The extension service worker lifecycle). Incognito profile startup does not fire onStartup, even in split incognito mode (browser.runtime).

When Chrome stops the extension service worker

Section titled “When Chrome stops the extension service worker”

Normally Chrome terminates the worker when:

  • 30 seconds pass without activity (incoming events or extension API calls reset the timer)
  • A single event or API call runs longer than 5 minutes
  • A fetch() response takes longer than 30 seconds to arrive

Nevertheless, you should design your service worker to be resilient against unexpected termination.

— Chrome, The extension service worker lifecycle

Recent Chrome versions extend lifetime for active WebSockets (message traffic resets the idle timer from Chrome 116), long-lived ports, browser.debugger sessions, native messaging, and certain prompt-based APIs (The extension service worker lifecycle, Use WebSockets in service workers).

Manifest V2’s runtime.onSuspend applied to event pages; design MV3 workers assuming no reliable suspend callback—persist state early via browser.storage rather than globals (Migrate to a service worker).

runtime.onInstalled and extension update lifecycle

Section titled “runtime.onInstalled and extension update lifecycle”

The Runtime API is the main surface for install/update messaging and metadata.

browser.runtime.onInstalled fires when the extension is first installed, updated to a new version, or when Chrome itself is updated (browser.runtime). The details.reason field uses OnInstalledReason values such as install, update, browser_update, enable, startup, and reload (browser.runtime).

Reloading an unpacked extension counts as an update, so onInstalled runs with reason update, including reload via browser.runtime.reload() (browser.runtime).

Typical uses from the cluster:

There is no event when your extension is uninstalled; use setUninstallURL if you need post-uninstall feedback (Manifest V2 FAQ).

Chrome installs extension updates when the extension is idle—primarily when the service worker is not running and no extension UI pages (popup, options, side panel) are open. An active content script does not block idle status (The Chrome Extension update lifecycle).

browser.runtime.onUpdateAvailable fires when a downloaded update is ready; installing it may require the worker to go idle or calling browser.runtime.reload() (browser.runtime). requestUpdateCheck() can trigger a store check but is throttled (The Chrome Extension update lifecycle).

Events in service workers: register listeners in global scope

Section titled “Events in service workers: register listeners in global scope”

Extension service workers handle both web-style service worker events and extension API events (Events in service workers).

Why listeners must be synchronous and top-level

Section titled “Why listeners must be synchronous and top-level”

Handlers must be declared in the global scope at the top level of the script so Chrome registers them on first execution and can dispatch events after a restart:

Event handlers in service workers need to be declared in the global scope, meaning they should be at the top level of the script and not be nested inside functions.

— Chrome, Events in service workers

Do not register listeners inside onInstalled, inside storage.local.get callbacks, or other async nests—the pattern that worked on persistent background pages will miss events after the worker restarts (Manage events with background scripts, Handle events with service workers).

Common event namespaces include browser.action, browser.runtime, browser.storage.onChanged, browser.notifications, browser.webNavigation, and others (Events in service workers).

For network work in the worker, prefer fetch() over XMLHttpRequest(); XHR in other contexts can still wake the worker’s fetch handler (Cross-origin network requests).

Other extension pages should talk to the service worker via sendMessage() / onMessage (or long-lived ports), not getBackgroundPage() (Update your code).

Offscreen documents: DOM and page APIs from the service worker

Section titled “Offscreen documents: DOM and page APIs from the service worker”

Service workers cannot access the DOM. The Offscreen API opens a hidden packaged HTML page for DOM APIs without showing a window.

Service workers don’t have DOM access, and many websites have content security policies that limit the functionality of content scripts. The Offscreen API allows the extension to use DOM APIs in a hidden document without interrupting the user experience by opening new windows or tabs.

— Chrome, browser.offscreen

Constraints that matter in practice:

  • URL must be a static HTML file in the extension package
  • Only browser.runtime is available inside the offscreen document for extension APIs—use runtime messaging
  • An installed extension may have only one offscreen document open at a time (one per profile in split incognito mode)
  • createDocument() requires url, reasons, and justification (browser.offscreen)

Before messaging, ensure the document exists—e.g. with runtime.getContexts({ contextTypes: ['OFFSCREEN_DOCUMENT'], documentUrls: [...] }) or a creation guard against concurrent createDocument() calls (browser.offscreen). Close offscreen documents when finished (Use geolocation).

Patterns that need navigator or window in the background (geolocation, clipboard, scraping) belong in offscreen code coordinated by the worker (Use geolocation, Migrate to a service worker).

Migrate from background scripts: checklist for Manifest V3

Section titled “Migrate from background scripts: checklist for Manifest V3”

Manifest V3 migration checklist and Migrate to a service worker group the mechanical changes:

Task Why
Replace background.scripts with background.service_worker Single string entry; remove persistent
Move DOM/window usage to offscreen documents Workers have no DOM
Replace localStorage with browser.storage.local Survives worker termination
Register listeners synchronously at load Survives restarts
Replace XMLHttpRequest() with fetch() XHR unavailable in the worker
Persist state; replace setTimeout/setInterval with browser.alarms Timers do not survive dormancy (Migrate to event-driven background scripts)

Chrome does not plan general support for persistent extension service workers—the model stays event-driven and ephemeral (Known issues when migrating to Manifest V3).

Keep the service worker alive: when extension APIs reset the timer

Section titled “Keep the service worker alive: when extension APIs reset the timer”

Default design: let the worker stop when idle. For long async work without extension API calls, Chrome documents a waitUntil() helper that periodically calls a trivial API such as browser.runtime.getPlatformInfo every 25 seconds until a promise finishes (Migrate to a service worker).

Continuous heartbeat via storage writes is documented only for exceptional enterprise/education cases on managed devices; the extensions team discourages indefinite keep-alive elsewhere (Migrate to a service worker). WebSocket clients should exchange messages within the 30-second activity window (for example a 20-second keepalive ping) (Use WebSockets in service workers).

On chrome://extensions, use Inspect views next to the service worker link to open DevTools (Debug extensions). In DevTools Application → Service Workers, you can see status, force update, and stop the worker to simulate restart (Debug extensions).

End-to-end testing for Chrome Extensions recommends loading the built package in a real browser via Puppeteer, Playwright, Selenium, or WebDriverIO. Test Chrome Extensions with Puppeteer shows waiting for a service_worker target before driving UI.

Test service worker termination with Puppeteer stresses that global variables die when the worker stops—tests should persist via browser.storage.local and return true from onMessage when using async sendResponse. Note: Selenium/ChromeDriver may attach a debugger and prevent automatic termination (End-to-end testing for Chrome Extensions).

Chrome Web Store best practices also recommend Puppeteer end-to-end tests plus manual checks across browser versions, OSs, and network conditions.

  • Relying on in-memory globals for state across messages or alarms
  • Registering event listeners inside async initialization
  • Using XMLHttpRequest() inside the service worker
  • Assuming onInstalled means reason === 'install' when developing unpacked (reload → update)
  • Leaving DevTools attached while judging 30-second shutdown
  • Opening multiple offscreen documents or forgetting closeDocument()
  • Expecting uninstall notifications—only install/update/browser update paths exist (Manifest V2 FAQ)
  1. Load the unpacked extension on chrome://extensions, confirm the service worker shows active or inactive after ~30 seconds with DevTools closed, per The extension service worker lifecycle.
  2. Trigger runtime.onInstalled paths (install, reload as update) and verify initialization logic using the Inspect views flow in Debug extensions.
  3. Stop the worker from DevTools Application → Service Workers, then exercise messaging and alarms to confirm behaviour matches Test service worker termination with Puppeteer.
  4. If you use offscreen documents, confirm a single document via runtime.getContexts patterns in browser.offscreen and tear it down when done.
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about, and we will correct or clarify it.