Structure

Background service worker

Configure your extension's background service worker.

An extension's service worker is a powerful script that runs in the background, separate from other parts of the extension. It's loaded when it is needed, and unloaded when it goes dormant. Once loaded, an extension service worker generally runs as long as it is actively receiving events, though it can shut down. Like its web counterpart, an extension service worker cannot access the DOM, though you can use it if needed with offscreen documents.

Extension service workers are more than network proxies (as web service workers are often described), they run in a separate service worker context. For example, when in this context, you no longer need to worry about CORS and can fetch resources from any origin.

In addition to the standard service worker events, they also respond to extension events such as navigating to a new page, clicking a notification, or closing a tab. They're also registered and updated differently from web service workers.

It's common to offload heavy computation to the background service worker, so you should always try to do resouce-expensive operations there and send results using Messages API to other parts of the extension.

Code for the background service worker is located at src/app/background directory - you need to define index.ts file inside to allow Plasmo to include your script in the build.

src/app/background/index.ts
export {};
 
console.log(
  "Background service worker is running! Edit `src/app/background` and save to reload.",
);

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!

To see the service worker in action, reload the extension, then open its "Service Worker inspector":

Service Worker inspector

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

Service Worker console

To communicate with the service worker from other parts of the extension, you can use the Messaging API.

Persisting state

Service workers in dev mode always remain in active 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 our backend API.

Last updated on

On this page

Ship your startup everywhere. In minutes.Get TurboStarter