Chrome extension development manual·Extension service worker life cycle

> The extension service worker lifecycle

Extending the service worker lifecycle

Published on Tuesday, May 2, 2023 • Updated on Tuesday, June 27, 2023
Published on Tuesday, May 2, 2023 · Updated on Tuesday, June 27, 2023

Table of contents table of contents

  • Installation installation method
    • ServiceWorkerRegistration.install
    • chrome.runtime.onInstalled
    • ServiceWorkerRegistration.active
  • Extension startup extension startup
  • Idle and shutdown Idle and shutdown
    • Persist data rather than using global variablesPersist
      data instead of using global variables
    • Choose a minimum Chrome versionChoose a
      minimum Chrome version

Extension service workers respond to both the standard service worker events and to events in extension namespaces. They are presented together because often one type follows another during an extensions use. Extension service workers respond to both the standard service worker events and to events in extension namespaces
. event. They are put together because one type usually follows the other during the use of extensions.

# Installation installation method

Installation occurs when the user installs or updates a service worker from the Chrome Web Store or when they load or update an unpacked extension using the chrome://extensionspage. Three events occur in the order below.
Installation occurs when an unpacked extension is loaded or updated using this page. Three events occur in the following order.

# ServiceWorkerRegistration.install

The first event fired during installation is a web service workers install event
.

# chrome.runtime.onInstalled

Next is the extensions onInstalledevent, which is fired when the extension (not the service worker) is first installed, when the extension is updated to a new version, and when Chrome is updated to a new version. Use this event to set a state or for one-time initialization, such as a context menu.
Next are the extension's events, which are fired when the extension (not the service worker) is first installed, when the extension is updated to a new version, and when Chrome is updated to a new version. event. Use this event to set state or do one-time initialization, such as a context menu.

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

# ServiceWorkerRegistration.active


Finally, the service workers activate event is fired. Note that unlike web service workers, this event is fired immediately after installation of an extension because there is nothing comparable to a page reload in an extension. . Note that unlike the web service worker thread, this event fires immediately after the extension is installed, since there is nothing in the extension to compare to a page reload.

# Extension startup Extension startup

When a user profile starts, the

chrome.runtime.onStartup

event fires but no service worker events are invoked.
When a user profile starts, events fire but no service worker events are invoked.

# Idle and shutdown Idle and shutdown

Normally, Chrome terminates a service worker when one of the following conditions is met:
Normally, Chrome terminates a service worker when one of the following conditions is met:

  • After 30 seconds of inactivity. Receiving an event or calling an extension API resets this timer
    . Receiving an event or calling an extension API resets this timer.
  • When a single request, such as an event or API call, takes longer than 5 minutes to process.
    When a single request, such as an event or API call, takes longer than 5 minutes to process.
  • When a fetch() response takes more than 30 seconds to arrive.
    fetch() response arrives in more than 30 seconds.


Events and calls to extension APIs reset these timers, and if the service worker has gone dormant, an incoming event will revive them. Nevertheless, you should design your service worker to be resilient against unexpected termination. Set these timers and if the service worker goes to sleep, incoming events will cause them to resume. However, you should design your service workers to be resistant to unexpected termination.

To optimize the resource consumption of your extension, avoid keeping your service worker alive indefinitely if possible. Test your extensions to ensure that youre not doing this unintentionally. To optimize the resource consumption of your extension, avoid keeping your
service worker alive indefinitely if possible. state. Test your extension to make sure you're not doing this accidentally.

# Persist data rather than using global variables

Persist data instead of using global variables

Any global variables you set will be lost if the service worker shuts down. Instead of using global variables, save values ​​to storage. Your options are listed below. Note that the Web Storage API is not available for extension service workers
. , any global variables you set will be lost. Don't use global variables, instead save the value to storage. Your options are listed below. Note that the Web Storage API does not work with extension service workers.

chrome.storage API chrome.storage API

An extension API that offers multiple types of storage; local, session, managed (domain), and sync. This API stores JSON objects identified and retrieved with developer-defined keys. This type of storage will not be removed when a user clears the web cache.
Provides extended API for multiple storage types; local, session, hosted (domain) and synchronized. This API stores JSON objects that are identified and retrieved using developer-defined keys. This type of storage is not deleted when the user clears the web cache.

IndexedDB API IndexedDB API

A low-level API for client-side storage of structured data, including files and blobs. This API provides primitives for creating transactional data storage and retrieval. Although this API is often too complicated for simple use cases, a number of third-party storage solutions are built on top of it.
Low-level API for client-side storage of structured data, including files and blobs. This API provides primitives for creating transactional data storage and retrieval. While this API is often too complex for simple use cases, many third-party storage solutions are built on top of it.

CacheStorage API CacheStorage API

A persistent storage mechanism for Request and Response object pairs. This API was designed specifically for web service workers and is used to retrieve data from an endpoint. There are a variety of ways to use this API depending on whether and how critical it is that users see up-to-date data. For more information, see The Offline Cookbook. Unless you're specifically proxying network requests via the fetch handler, you should use .a chrome.storagepersistent
storage mechanism for request and response object pairs. This API is designed specifically for web service workers to retrieve data from endpoints. There are multiple ways to use this API depending on whether the user sees the latest data and how important it is to see the latest data. For more information, see Offline Recipes. Unless you are proxying network requests through a fetch handler, you should use .

# Choose a minimum Chrome version

Choose the lowest Chrome version

Since the release of Manifest V3, weve made several improvements to service worker lifetimes. This means that if your Manifest V3 extension supports earlier versions of Chrome, there are conditions you will need to be aware of. If these conditions do not affect your extension, you can move on from this section. If they do, consider specifying a minimum Chrome version in your manifest.
Since the release of ManifestV3, we have made some improvements to the service worker lifecycle. This means that if your Manifest V3 extension supports earlier versions of Chrome, there are some conditions to be aware of. If these conditions do not affect your extension, you can continue from this section. If so, consider specifying the minimum Chrome version in the manifest.

#Chrome 116 Chrome 116

Chrome 116 introduced the following service worker lifetime improvements:
Chrome 116 introduced the following Service Worker lifetime improvements:

  • Active WebSocketconnections now extend extension service worker lifetimes. Sending or receiving messages across a WebSocketin an extension service worker resets the service workers idle timer.
    Active connections now extend extension service worker lifetimes. Sending or receiving a message in an extended service worker process resets the service worker process's idle timer.

  • Additional extension APIs are allowed to go past the five-minute timeout period for extension service workers. These APIs display a user prompt and thus may reasonably take longer than five minutes to resolve. These include

    desktopCapture.chooseDesktopMedia()
    

    ,

    identity.launchWebAuthFlow()
    

    ,

    management.uninstall()
    

    , and

    permissions.request()
    

    .For
    extension service workers, additional extension APIs are allowed beyond the 5-minute timeout. These APIs display user prompts so may take more than five minutes to resolve. Including,, and.

#Chrome114 Chrome114


Sending a message using long-lived messaging keeps the service worker alive. Previously, opening a port reset the timers, but sending a message would not. Opening a port no longer resets the timers. Stay active. Previously, opening a port would reset the timer, but sending a message would not. Opening a port no longer resets the timer.

#Chrome110 Chrome110

Extension API calls reset the timers. Before this, only running event handlers would keep a service worker alive. Any events that were queued, but for which a handler had not been called would not cause a reset
. Previously, service workers could only be kept alive by running event handlers. Any queued event for which a handler has not yet been called will not cause a reset.

#Chrome 109 Chrome 109

Messages sent from an offscreen document reset the timers.
Messages sent from an offscreen document reset the timers.

#Chrome105 Chrome105

Connecting to a native messaging host using

chrome.runtime.connectNative()

will keep a service worker alive. If the host process crashes or is shut down, the port is closed and the service worker will terminate after timers complete. Guard against this by calling

chrome.runtime.connectNative()

in the ports onDisconnect event handler.
Using a connection to the native messaging host will keep the service worker alive. If the host process crashes or shuts down, the port will be closed and the service worker thread will terminate after the timer expires. Prevent this by calling the port's onDisconnect event handler.

Updated on Tuesday, June 27, 2023 • Improve articleUpdated
on Tuesday, June 27, 2023 · Improve article

Guess you like

Origin blog.csdn.net/qq_35606400/article/details/132061805