feat: service worker preload scripts for improved extensions support (#44411)

* feat: preload scripts for service workers

* feat: service worker IPC

* test: service worker preload scripts and ipc
This commit is contained in:
Sam Maddock 2025-01-31 09:32:45 -05:00 committed by GitHub
parent bc22ee7897
commit 26da3c5d6e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
67 changed files with 2103 additions and 298 deletions

View file

@ -0,0 +1,75 @@
## Class: IpcMainServiceWorker
> Communicate asynchronously from the main process to service workers.
Process: [Main](../glossary.md#main-process)
> [!NOTE]
> This API is a subtle variation of [`IpcMain`](ipc-main.md)—targeted for
> communicating with service workers. For communicating with web frames,
> consult the `IpcMain` documentation.
<!-- TODO(samuelmaddock): refactor doc gen to allow generics to reduce duplication -->
### Instance Methods
#### `ipcMainServiceWorker.on(channel, listener)`
* `channel` string
* `listener` Function
* `event` [IpcMainServiceWorkerEvent][ipc-main-service-worker-event]
* `...args` any[]
Listens to `channel`, when a new message arrives `listener` would be called with
`listener(event, args...)`.
#### `ipcMainServiceWorker.once(channel, listener)`
* `channel` string
* `listener` Function
* `event` [IpcMainServiceWorkerEvent][ipc-main-service-worker-event]
* `...args` any[]
Adds a one time `listener` function for the event. This `listener` is invoked
only the next time a message is sent to `channel`, after which it is removed.
#### `ipcMainServiceWorker.removeListener(channel, listener)`
* `channel` string
* `listener` Function
* `...args` any[]
Removes the specified `listener` from the listener array for the specified
`channel`.
#### `ipcMainServiceWorker.removeAllListeners([channel])`
* `channel` string (optional)
Removes listeners of the specified `channel`.
#### `ipcMainServiceWorker.handle(channel, listener)`
* `channel` string
* `listener` Function\<Promise\<any\> | any\>
* `event` [IpcMainServiceWorkerInvokeEvent][ipc-main-service-worker-invoke-event]
* `...args` any[]
#### `ipcMainServiceWorker.handleOnce(channel, listener)`
* `channel` string
* `listener` Function\<Promise\<any\> | any\>
* `event` [IpcMainServiceWorkerInvokeEvent][ipc-main-service-worker-invoke-event]
* `...args` any[]
Handles a single `invoke`able IPC message, then removes the listener. See
`ipcMainServiceWorker.handle(channel, listener)`.
#### `ipcMainServiceWorker.removeHandler(channel)`
* `channel` string
Removes any handler for `channel`, if present.
[ipc-main-service-worker-event]:../api/structures/ipc-main-service-worker-event.md
[ipc-main-service-worker-invoke-event]:../api/structures/ipc-main-service-worker-invoke-event.md

View file

@ -114,6 +114,7 @@ A `string` representing the current process's type, can be:
* `browser` - The main process
* `renderer` - A renderer process
* `service-worker` - In a service worker
* `worker` - In a web worker
* `utility` - In a node process launched as a service

View file

@ -15,6 +15,19 @@ _This class is not exported from the `'electron'` module. It is only available a
Returns `boolean` - Whether the service worker has been destroyed.
#### `serviceWorker.send(channel, ...args)` _Experimental_
- `channel` string
- `...args` any[]
Send an asynchronous message to the service worker process via `channel`, along with
arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA],
just like [`postMessage`][], so prototype chains will not be included.
Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception.
The service worker process can handle the message by listening to `channel` with the
[`ipcRenderer`](ipc-renderer.md) module.
#### `serviceWorker.startTask()` _Experimental_
Returns `Object`:
@ -25,6 +38,10 @@ Initiate a task to keep the service worker alive until ended.
### Instance Properties
#### `serviceWorker.ipc` _Readonly_ _Experimental_
An [`IpcMainServiceWorker`](ipc-main-service-worker.md) instance scoped to the service worker.
#### `serviceWorker.scope` _Readonly_ _Experimental_
A `string` representing the scope URL of the service worker.
@ -32,3 +49,6 @@ A `string` representing the scope URL of the service worker.
#### `serviceWorker.versionId` _Readonly_ _Experimental_
A `number` representing the ID of the specific version of the service worker script in its scope.
[SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
[`postMessage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

View file

@ -107,8 +107,6 @@ Returns `Promise<ServiceWorkerMain>` - Resolves with the service worker when it'
Starts the service worker or does nothing if already running.
<!-- TODO(samuelmaddock): extend example to send IPC after starting worker -->
```js
const { app, session } = require('electron')
const { serviceWorkers } = session.defaultSession
@ -120,7 +118,8 @@ app.on('browser-window-created', async (event, window) => {
for (const scope of workerScopes) {
try {
// Ensure worker is started
await serviceWorkers.startWorkerForScope(scope)
const serviceWorker = await serviceWorkers.startWorkerForScope(scope)
serviceWorker.send('window-created', { windowId: window.id })
} catch (error) {
console.error(`Failed to start service worker for ${scope}`)
console.error(error)

View file

@ -1,5 +1,6 @@
# IpcMainEvent Object extends `Event`
* `type` String - Possible values include `frame`
* `processId` Integer - The internal ID of the renderer process that sent this message
* `frameId` Integer - The ID of the renderer frame that sent this message
* `returnValue` any - Set this to the value to be returned in a synchronous message

View file

@ -1,5 +1,6 @@
# IpcMainInvokeEvent Object extends `Event`
* `type` String - Possible values include `frame`
* `processId` Integer - The internal ID of the renderer process that sent this message
* `frameId` Integer - The ID of the renderer frame that sent this message
* `sender` [WebContents](../web-contents.md) - Returns the `webContents` that sent the message

View file

@ -0,0 +1,11 @@
# IpcMainServiceWorkerEvent Object extends `Event`
* `type` String - Possible values include `service-worker`.
* `serviceWorker` [ServiceWorkerMain](../service-worker-main.md) _Readonly_ - The service worker that sent this message
* `versionId` Number - The service worker version ID.
* `session` Session - The [`Session`](../session.md) instance with which the event is associated.
* `returnValue` any - Set this to the value to be returned in a synchronous message
* `ports` [MessagePortMain](../message-port-main.md)[] - A list of MessagePorts that were transferred with this message
* `reply` Function - A function that will send an IPC message to the renderer frame that sent the original message that you are currently handling. You should use this method to "reply" to the sent message in order to guarantee the reply will go to the correct process and frame.
* `channel` string
* `...args` any[]

View file

@ -0,0 +1,6 @@
# IpcMainServiceWorkerInvokeEvent Object extends `Event`
* `type` String - Possible values include `service-worker`.
* `serviceWorker` [ServiceWorkerMain](../service-worker-main.md) _Readonly_ - The service worker that sent this message
* `versionId` Number - The service worker version ID.
* `session` Session - The [`Session`](../session.md) instance with which the event is associated.

View file

@ -1,6 +1,6 @@
# PreloadScriptRegistration Object
* `type` string - Context type where the preload script will be executed.
Possible values include `frame`.
Possible values include `frame` or `service-worker`.
* `id` string (optional) - Unique ID of preload script. Defaults to a random UUID.
* `filePath` string - Path of the script file. Must be an absolute path.

View file

@ -1,6 +1,6 @@
# PreloadScript Object
* `type` string - Context type where the preload script will be executed.
Possible values include `frame`.
Possible values include `frame` or `service-worker`.
* `id` string - Unique ID of preload script.
* `filePath` string - Path of the script file. Must be an absolute path.