Persistent Service Worker in Chrome Extension
Service workers (SWs) in Chrome extensions are not inherently persistent, meaning they can be forcibly terminated by the browser after a certain period of inactivity. This can be a problem for extensions that rely on SWs to intercept and modify network requests, especially if the request is time-consuming or the user navigates away from the page before the request is complete.
Workarounds
There are several workarounds available to keep a SW running persistently in Chrome extensions:
-
Bug Exploit (Chrome 110 ): Call any asynchronous Chrome API function to keep the worker active for an additional 30 seconds. This exploit has been acknowledged as a feature by the Chromium team and is expected to remain in place for the foreseeable future.
-
Offscreen API (Chrome 109 ): Create an offscreen document and send a message from it to the SW every 30 seconds or less. This technique takes advantage of the fact that offscreen documents have an unlimited lifetime in recent versions of Chrome.
-
NativeMessaging API (Chrome 105 ): Connect the SW to a native host process using the chrome.runtime.connectNative function. As long as the connection is maintained, the SW will remain active.
-
WebSocket API (Chrome 116 ): Establish a WebSocket connection and exchange messages every 25 seconds or less to keep it active.
-
Chrome Messaging API: Ping another tab in the extension by sending messages back and forth, thereby keeping the SW alive.
-
Dedicated Tab: Instead of using a SW, open a dedicated tab with an extension page that acts as a visible background page. This page can be used to intercept requests and maintain the state of the extension.
Caution
It's important to use these workarounds judiciously and only when necessary. Persistent SWs can consume memory and resources, so they should be disabled when not in use. Additionally, saving and restoring the state of the extension in storage is crucial to protect against crashes.
The above is the detailed content of How Can I Keep a Service Worker Persistent in a Chrome Extension?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn