How service workers differ from MV2 background pages
Because the service worker can be terminated at any time, do not rely on in-memory variables to persist state between events. Write anything you need to keep to
chrome.storage.Declare the service worker
Inmanifest.json:
"type": "module" if you want to use ES module import syntax.
A minimal background.js
Common events to listen for
runtime.onInstalled
runtime.onInstalled
Fires when the extension is first installed, updated, or Chrome is updated. Use this to set default storage values or open a welcome page.
tabs.onUpdated
tabs.onUpdated
Fires when a tab’s URL, title, or loading state changes. Requires the
"tabs" permission.alarms.onAlarm
alarms.onAlarm
Fires when a scheduled alarm triggers. Use this for periodic background tasks. Requires the
"alarms" permission.runtime.onMessage
runtime.onMessage
Fires when a content script, popup, or options page calls
chrome.runtime.sendMessage. This is the primary way other extension contexts communicate with the background worker.Communicate between content scripts and the service worker
Send messages from a content script to the background worker:Make cross-origin API requests
The service worker is the right place forfetch() calls to external APIs that might be blocked by a page’s Content Security Policy:
Prompt Extensy to add service worker logic
Describe the event-driven behavior you want:
“Every 15 minutes, fetch the latest headlines from https://newsapi.org and update the extension badge with the count of new articles.”
“When the user visits any page on amazon.com, send a message to the content script to highlight items that are on my wishlist.”
“On install, open the options page so the user can enter their API key.”