> The extension service worker lifecycle
扩展服务工作者生命周期
Published on Tuesday, May 2, 2023 • Updated on Tuesday, June 27, 2023
发布于2023年5月2日星期二·更新于2023年6月27日星期二
Table of contents 目录
- Installation 安装方式
- ServiceWorkerRegistration.install
- chrome.runtime.onInstalled
- ServiceWorkerRegistration.active
- Extension startup 扩展启动
- Idle and shutdown 怠速和停机
- Persist data rather than using global variables
持久化数据而不是使用全局变量 - Choose a minimum Chrome version
选择最低Chrome版本
- Persist data rather than using global variables
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.
扩展服务工作线程同时响应标准服务工作线程事件和扩展命名空间中的事件。它们被放在一起是因为在扩展的使用过程中,一种类型通常会跟随另一种类型。
# Installation 安装方式
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://extensions
page. Three events occur in the order below.
当用户从Chrome网上应用商店安装或更新Service Worker,或者使用该页面加载或更新解包的扩展程序时,就会发生安装。三个事件按以下顺序发生。
# ServiceWorkerRegistration.install
The first event fired during installation is a web service workers install event.
安装期间激发的第一个事件是Web服务工作进程的安装事件。
# chrome.runtime.onInstalled
Next is the extensions
onInstalled
event, 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.
接下来是扩展的事件,当扩展(不是service worker)首次安装时,当扩展更新到新版本时,以及当Chrome更新到新版本时,都会触发该事件。使用此事件设置状态或进行一次性初始化,如上下文菜单。
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.
最后,服务工作者的activate事件被触发。请注意,与Web服务工作线程不同,此事件在安装扩展后立即激发,因为在扩展中没有什么可与页面重新加载相比。
# Extension startup 扩展启动
When a user profile starts, the
chrome.runtime.onStartup
event fires but no service worker events are invoked.
当用户配置文件启动时,将触发事件,但不会调用任何服务工作进程事件。
# Idle and shutdown 怠速和停机
Normally, Chrome terminates a service worker when one of the following conditions is met:
通常情况下,当满足以下条件之一时,Chrome会终止service worker:
- After 30 seconds of inactivity. Receiving an event or calling an extension API resets this timer.
在30秒的不活动之后。接收事件或调用扩展API会重置此计时器。 - When a single request, such as an event or API call, takes longer than 5 minutes to process.
当单个请求(如事件或API调用)的处理时间超过5分钟时。 - When a fetch() response takes more than 30 seconds to arrive.
fetch()响应到达时间超过30秒。
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.
事件和对扩展API的调用会重置这些计时器,如果service worker进入休眠状态,则传入的事件会使它们恢复。不过,您应该将服务工作者设计为能够抵御意外终止。
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.
要优化扩展的资源消耗,请尽可能避免让service worker无限期地处于活动状态。测试您的扩展以确保您不是无意中这样做的。
# Persist data rather than 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.
如果service worker关闭,您设置的任何全局变量都将丢失。不要使用全局变量,而是将值保存到存储中。下面列出了您的选项。请注意,Web Storage API不适用于扩展服务工作者。
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.
提供多种存储类型的扩展API;本地、会话、托管(域)和同步。此API存储使用开发人员定义的键标识和检索的JSON对象。当用户清除Web缓存时,不会删除这种类型的存储。
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.
用于客户端存储结构化数据(包括文件和blob)的低级API。此API提供用于创建事务性数据存储和检索的原语。虽然这个API对于简单的用例来说往往过于复杂,但许多第三方存储解决方案都是在它之上构建的。
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 chrome.storage
.
请求和响应对象对的持久存储机制。此API专门为Web服务工作者设计,用于从端点检索数据。根据用户是否看到最新数据以及查看最新数据的重要性,有多种方法可以使用此API。有关更多信息,请参阅离线食谱。除非你是通过fetch处理程序来代理网络请求,否则你应该使用。
# Choose a minimum Chrome version
选择最低Chrome版本
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.
自从ManifestV3发布以来,我们对服务工作者的生命周期做了一些改进。这意味着,如果您的Manifest V3扩展程序支持早期版本的Chrome,则需要注意一些条件。如果这些条件不影响您的扩展,您可以从本节继续。如果是,请考虑在清单中指定最低Chrome版本。
# Chrome 116 铬116
Chrome 116 introduced the following service worker lifetime improvements:
Chrome 116引入了以下Service Worker生命周期改进:
-
Active
WebSocket
connections now extend extension service worker lifetimes. Sending or receiving messages across aWebSocket
in an extension service worker resets the service workers 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()
.
对于扩展服务工作者,允许额外的扩展API超过5分钟的超时时间。这些API显示用户提示,因此可能需要超过五分钟的时间来解决。包括、、和。
# Chrome 114 铬114
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.
使用长期消息传递发送消息可使服务工作线程保持活动状态。以前,打开端口会重置计时器,但发送消息不会。打开端口不再重置计时器。
# Chrome 110 铬110
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.
扩展API调用重置计时器。在此之前,只有运行事件处理程序才能使服务工作线程保持活动状态。任何已排队但尚未为其调用处理程序的事件都不会导致重置。
# Chrome 109 铬109
Messages sent from an offscreen document reset the timers.
从屏幕外文档发送的消息重置计时器。
# Chrome 105 铬105
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.
使用连接到本机消息传递主机将使service worker保持活动状态。如果主机进程崩溃或关闭,端口将关闭,服务工作线程将在计时器结束后终止。通过调用端口的onDisconnect事件处理程序来防止这种情况。
Updated on Tuesday, June 27, 2023 • Improve article
更新于2023年6月27日星期二·改善文章