• Browser Extension SDK
  • Background SW

Background Service Worker

An extension's background service worker is powerful because it runs in the service worker context. 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 💪

export {}
  "Live now; make now always the most precious time. Now will never come again."

NOTE: 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 for a complete example.

Persisting states

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.

Last updated on December 2, 2022