Framework
Background SW

Background Service Worker

An extension's background service worker is powerful because it runs in the service worker context (opens in a new tab). For example, when in this context, you no longer need to worry about CORS and can fetch resources from any origin. It is also common to offload heavy computation to the background service worker.

To build your first background service worker, create a background.ts file in the root directory, and start hacking 💪

background.ts
export {}
 
console.log(
  "Live now; make now always the most precious time. Now will never come again."
)
⚠️

Since Plasmo's default Typescript configuration treats all source files as modules, if you don't have any imports or exports in your code, you'll have to add an export {} line at the start of your file. You will see this warning when creating your first content script!

Reload the extension, then open its "Service Worker inspector":

Service Worker Inspector

You should see what we've logged in the inspector:

background sw picard log

See with-background (opens in a new tab) for a complete example.

Persisting state

The worker becomes idle after a few seconds of inactivity, and the browser will kill its process entirely after 5 minutes. This means all state (variables, etc.) is lost unless you use a storage engine.

The simplest way to persist your background service worker's state is to use the storage API.

The more advanced way is to send the state to a remote database via a fetch call or WebSocket.