Skip to content

Workbox ​

Class workbox-window

A class to aid in handling service worker registration, updates, and reacting to service worker lifecycle events.

Constructor ​

ts
new Workbox(scriptURL: string | TrustedScriptURL, registerOptions?: object)

Creates a new Workbox instance with a script URL and service worker options. The script URL and options are the same as those used when calling navigator.serviceWorker.register(scriptURL, options).

Parameters

  • scriptURL – The service worker script associated with this instance. Using a TrustedScriptURL is supported.

  • registerOptions – The service worker options associated with this instance.

Methods ​

getSW() ​

ts
getSW(): Promise<ServiceWorker>

Resolves with a reference to a service worker that matches the script URL of this instance, as soon as it's available.

If, at registration time, there's already an active or waiting service worker with a matching script URL, it will be used (with the waiting service worker taking precedence over the active service worker if both match, since the waiting service worker would have been registered more recently). If there's no matching active or waiting service worker at registration time then the promise will not resolve until an update is found and starts installing, at which point the installing service worker is used.

Returns:

messageSkipWaiting() ​

ts
messageSkipWaiting(): void

Sends a {type: 'SKIP_WAITING'} message to the service worker that's currently in the waiting state associated with the current registration.

If there is no current registration or no service worker is waiting, calling this will have no effect.

messageSW() ​

ts
messageSW(data: object): Promise<any>

Sends the passed data object to the service worker registered by this instance (via workbox-window.Workbox#getSW) and resolves with a response (if any).

A response can be set in a message handler in the service worker by calling event.ports[0].postMessage(...), which will resolve the promise returned by messageSW(). If no response is set, the promise will never resolve.

Parameters

  • data – An object to send to the service worker

Returns:

register() ​

ts
register(options?: { immediate?: boolean }): Promise<ServiceWorkerRegistration | undefined>

Registers a service worker for this instances script URL and service worker options. By default this method delays registration until after the window has loaded.

update() ​

ts
update(): Promise<void>

Checks for updates of the registered service worker.

Released under the MIT License.