electron/docs/api/service-worker-main.md

2.4 KiB

ServiceWorkerMain

An instance of a Service Worker representing a version of a script for a given scope.

Process: Main

Class: ServiceWorkerMain

Process: Main
This class is not exported from the 'electron' module. It is only available as a return value of other methods in the Electron API.

Instance Methods

serviceWorker.isDestroyed() Experimental

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, 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 module.

serviceWorker.startTask() Experimental

Returns Object:

  • end Function - Method to call when the task has ended. If never called, the service won't terminate while otherwise idle.

Initiate a task to keep the service worker alive until ended.

const { session } = require('electron')
const { serviceWorkers } = session.defaultSession

async function fetchData () {}

const versionId = 0
const serviceWorker = serviceWorkers.getWorkerFromVersionID(versionId)

serviceWorker?.ipc.handle('request-data', async () => {
  // Keep service worker alive while fetching data
  const task = serviceWorker.startTask()
  try {
    return await fetchData()
  } finally {
    // Mark task as ended to allow service worker to terminate when idle.
    task.end()
  }
})

Instance Properties

serviceWorker.ipc Readonly Experimental

An IpcMainServiceWorker instance scoped to the service worker.

serviceWorker.scope Readonly Experimental

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.