How do background scripts and service workers work in modern extensions, and what are the features of their lifecycle?
Background scripts are the core of any browser extension, acting as a central event dispatcher that coordinates popups, options pages, and content scripts. In the older Manifest V2 architecture, these scripts ran constantly in the background, which consumed a significant amount of RAM even when the extension was not performing active tasks.
With the transition to Manifest V3, background pages were replaced by background service workers, which operate on an event-driven architecture principle. This means that the runtime environment can terminate a service worker from memory at any time to save resources and restart it only when an event of interest occurs, such as an incoming network request or a triggered timer.
This approach requires developers to change their code-writing logic, as service workers do not support global state persistence in RAM between restarts. To store data and settings, developers must use persistent storage, such as the dedicated local storage API or browser-indexed databases.
Understanding the lifecycle features of service workers allows you to create more performant extensions that do not slow down the browser and do not cause user complaints about increased power consumption. Proper organization of event handling guarantees the stability and predictability of the add-in's behavior in various use cases.