欢迎 What's new in Chrome extensions Get help with Chrome extensions API reference Samples
欢迎 What's new in Chrome extensions Get help with Chrome extensions API reference Samples

Manage events with service workers

Published on Updated on

Extensions are event-based programs used to modify or enhance the Chrome browsing experience. Events are browser triggers, such as navigating to a new page, removing a bookmark, or closing a tab. Extensions monitor these events using scripts in an extension service worker (previously called a background script), which then executes specified instructions.

An extension service worker is loaded when it is needed, and unloaded when it goes dormant. Examples include:

  • The extension is first installed or updated to a new version.
  • An extension event is dispatched.
  • A content script or other extension sends a message.

Once it has been loaded, an extension service worker generally runs as long as it is actively receiving events. The browser will stop the service worker once it idles for a short period (30 seconds).

Opening a view doesn't cause the service worker to load, but only prevents it from closing once loaded.

Extension service workers stay dormant until an event they are listening for fires. At which point, they execute the appropriate event listener, idle, then unload.

Register the service worker

Extensions register their service worker in the manifest under the "background" field. This field uses the "service_worker" key, which specifies a single JavaScript file.

{
"name": "Awesome Test Extension",
...
"background": {
"service_worker": "background.js"
},
...
}

You can optionally specify an extra field of "type": "module" to include the service worker as an ES Module, which allows you to import further code. See ES modules in service workers for more information. For example:

  "background": {
"service_worker": "background.js",
"type": "module"
}

Initialize the extension

Listen to the runtime.onInstalled event to initialize an extension on installation. Use this event to set a state or for one-time initialization, such as a context menu.

chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
"id": "sampleContextMenu",
"title": "Sample Context Menu",
"contexts": ["selection"]
});
});

Set up listeners

Structure extension service workers around events the extension depends on. Defining functionally relevant events allows the service worker to lie dormant until those events are fired and prevents the extension from missing important triggers.

Make sure your event handlers are registered in global scope by not nesting them in functions. This ensures that they are registered synchronously on initial script execution, which Chrome needs in order to dispatch events to the listener right after the service worker starts up. Notice that in this example the listener for creating bookmarks is at the top level of the script.

Do

chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
"id": "sampleContextMenu",
"title": "Sample Context Menu",
"contexts": ["selection"],
});
});

// This will run when a bookmark is created.
chrome.bookmarks.onCreated.addListener(() => {
// do something
});

If you register the same listener asynchronously (for example, inside a runtime.onInstalled listener), the event will be dropped because the nested listener will not be registered when the browser attempts to dispatch it.

Don't

chrome.runtime.onInstalled.addListener(() => {
// ERROR! Events must be registered synchronously from the start of
// the service worker.
chrome.bookmarks.onCreated.addListener(() => {
// do something
});
});

Extensions can remove listeners from their background scripts by calling removeListener(). If all listeners for an event are removed, Chrome will no longer load the extension's background script for that event.

chrome.runtime.onMessage.addListener((message, sender, reply) => {
chrome.runtime.onMessage.removeListener(event);
});

Filter events

Use APIs that support event filters to restrict listeners to specific use cases. If an extension is listening for the tabs.onUpdated event to detect when a user navigates to a specific website, try using the webNavigation.onCompleted event with filters instead, as the tabs.onUpdated event does not support filters.

const filter = {
url: [
{
urlMatches: 'https://www.google.com/',
},
],
};

chrome.webNavigation.onCompleted.addListener(() => {
console.info("The user has loaded my favorite website!");
}, filter);

React to listeners

Listeners exist to trigger functionality once an event has fired. To react to an event, structure the desired reaction inside of the appropriate listener.

chrome.runtime.onMessage.addListener((message, callback) => {
const tabId = getForegroundTabId();
if (message.data === "setAlarm") {
chrome.alarms.create({delayInMinutes: 5});
} else if (message.data === "runLogic") {
chrome.scripting.executeScript({file: 'logic.js', tabId});
} else if (message.data === "changeColor") {
chrome.scripting.executeScript(
{func: () => document.body.style.backgroundColor="orange", tabId});
};
});

Unload extension service workers

Extension service workers do not receive any kind of unload or suspend event before they are stopped. This is because documents have unload and beforeUnload events, but web workers (and by extension service workers) do not have an equivalent event.

Updated on Improve article

We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.