Icon not found

Background Scripts

Background scripts are JavaScript files running in the background of an extension, providing persistent functionality such as handling events, storing data, and managing state. Extension.js supports background scripts in both background.scripts and background.service_worker formats, providing full control over long-lived processes within your extension.

How It Works?

Extension.js handles background scripts with the following features:

  1. Persistent Event Listeners: Background scripts can register persistent listeners to respond to browser events, API calls, or messages from content scripts.
  2. Hot-Module Replacement (HMR): For development, HMR is supported for background scripts declared under background.scripts, allowing faster feedback without restarting the extension.
  3. Service Worker Mode: When using background.service_worker, the background script will run as a service worker, aligning with Manifest V3’s requirements.

Background Script Support

The following fields in manifest.json are used to declare background scripts:

Manifest Field File Type Expected HMR Support
background.service_worker .js, .ts, .mjs No
background.scripts .js, .ts, .mjs Yes

Sample Background Script Declaration

Below is an example of how to declare a background script within the manifest.json file:

{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0",
  "background": {
    "service_worker": "./scripts/background-service-worker.js"
  }
}

This configuration defines background-service-worker.js as a service worker, which will persist and respond to events as needed by your extension.

Handling Additional Background Scripts

Place any additional background scripts that are not directly declared in manifest.json into the /scripts folder. Extension.js processes these files for inclusion in the build.

Example Usage:

scripts/
└── extra-background-script.js

Output Path

Background scripts will be output in the following directory structure:

dist/
  [browser]/
  ├── background/
  │   └── background-service-worker.js
  │   └── extra-background-script.js
  └── other-extension-files

Best Practices

  • Use Service Workers for Manifest V3 Compliance: With Manifest V3, consider using background.service_worker to ensure compatibility.
  • Organize Scripts in /scripts Folder: Maintain a structured /scripts folder for modularity and code clarity.
  • Optimize Long-Running Processes: Background scripts should be optimized for performance, especially in service worker mode where resources are limited.

Next Steps