Skip to content

@jakguru/vueprint / @jakguru/vueprint/pwa/worker / ServiceWorkerProvider

Class: ServiceWorkerProvider ​

@jakguru/vueprint/pwa/worker.ServiceWorkerProvider

The service worker provider acts as a wrapper around the functionality of the service worker to integrate it more closely with your application for functionality such as background messages, push notifications or application updates.

TIP

The Service Worker Provider is meant to be used in the service worker.

Accessing the Service Worker Provider ​

The Service Worker Provider should be imported from @jakguru/vueprint/pwa/worker

typescript
import { ServiceWorkerProvider } from '@jakguru/vueprint/pwa/worker'
import type { ServiceWorkerProviderOptions } from '@jakguru/vueprint/pwa/worker'

Using the Service Worker Provider ​

Configuration ​

The Service Worker Provider constructor accepts 2 arguments: self which is an instance of ServiceWorkerGlobalScope, and an optional ServiceWorkerProviderOptions object which has 2 properties:

KeyTypeDescription
firebaseFirebaseOptionsFirebase configuration object. Contains a set of parameters required by services in order to successfully communicate with Firebase server APIs and to associate client data with your Firebase project and Firebase application.
namespacestringThe namespace to use in the broadcast-channel to ensure that messages are sent and received between tabs

Adding Hooks ​

The Service Worker Provider includes an instance of the BusService under the hood, so you can use the same BusService.on, BusService.once, BusService.off, BusService.emit and BusService.await methods which you would normally use with the Bus Service.

Booting the Service Worker Provider ​

After initializing the Service Worker Provider instance, you will need to call instance.boot() to activate all of processes.

Available Service Worker Events ​

EventDescriptionAwaitedExperimental
sw:activateThe activate event of the ServiceWorkerGlobalScope interface is fired when a ServiceWorkerRegistration acquires a new ServiceWorkerRegistration.active worker.✅
sw:installThe install event of the ServiceWorkerGlobalScope interface is fired when a ServiceWorkerRegistration acquires a new ServiceWorkerRegistration.installing worker.✅
sw:fetchThe fetch event is fired in the service worker's global scope when the main app thread makes a network request. It enables the service worker to intercept network requests and send customized responses (for example, from a local cache).✅
sw:messageThe message event of the ServiceWorkerGlobalScope interface occurs when incoming messages are received. Controlled pages can use the ServiceWorker.postMessage() method to send messages to service workers. The service worker can optionally send a response back via the Client.postMessage(), corresponding to the controlled page.✅
sw:messageerrorThe messageerror event of the ServiceWorkerGlobalScope interface occurs when incoming messages can't be deserialized.
sw:notificationclickThe notificationclick event of the ServiceWorkerGlobalScope interface is fired to indicate that a system notification spawned by ServiceWorkerRegistration.showNotification() has been clicked.✅
sw:notificationcloseThe notificationclose event of the ServiceWorkerGlobalScope interface fires when a user closes a displayed notification spawned by ServiceWorkerRegistration.showNotification().✅
sw:pushThe push event is sent to a service worker's global scope (represented by the ServiceWorkerGlobalScope interface) when the service worker has received a push message.✅
sw:pushsubscriptionchangeThe pushsubscriptionchange event is sent to the global scope of a ServiceWorker to indicate a change in push subscription that was triggered outside the application's control.✅
sw:syncThe sync event of the ServiceWorkerGlobalScope interface is fired when the page (or worker) that registered the event with the SyncManager is running and as soon as network connectivity is available.✅
sw:backgroundfetchabortThe backgroundfetchabort event of the ServiceWorkerGlobalScope interface is fired when the user or the app itself cancels a background fetch operation.✅✅
sw:backgroundfetchclickThe backgroundfetchclick event of the ServiceWorkerGlobalScope interface is fired when the user clicks on the UI that the browser provides to show the user the progress of the background fetch operation.✅✅
sw:backgroundfetchfailThe backgroundfetchfail event of the ServiceWorkerGlobalScope interface is fired when a background fetch operation has failed: that is, when at least one network request in the fetch has failed to complete successfully.✅✅
sw:backgroundfetchsuccessThe backgroundfetchsuccess event of the ServiceWorkerGlobalScope interface is fired when a background fetch operation has completed successfully: that is, when all network requests in the fetch have completed successfully.✅✅
sw:canmakepaymentThe canmakepayment event of the ServiceWorkerGlobalScope interface is fired on a payment app's service worker to check whether it is ready to handle a payment. Specifically, it is fired when the merchant website calls new PaymentRequest().✅✅
sw:contentdeleteThe contentdelete event of the ServiceWorkerGlobalScope interface is fired when an item is removed from the indexed content via the user agent.✅✅
sw:cookiechangeThe cookiechange event of the ServiceWorkerGlobalScope interface is fired when a cookie change occurs that matches the service worker's cookie change subscription list.✅✅
sw:paymentrequestThe paymentrequest event of the ServiceWorkerGlobalScope interface is fired on a payment app when a payment flow has been initiated on the merchant website via the PaymentRequest.show() method.✅✅
sw:periodicsyncThe periodicsync event of the ServiceWorkerGlobalScope interface is fired at timed intervals, specified when registering a PeriodicSyncManager.✅✅

Practical Example ​

typescript
import { ServiceWorkerProvider } from '@jakguru/vueprint/pwa/worker'
import type { ServiceWorkerProviderOptions } from '@jakguru/vueprint/pwa/worker'
import type { FirebaseOptions } from 'firebase/app'

declare global {
  interface ImportMeta {
    env: Record<string, string>
  }
}

declare const self: ServiceWorkerGlobalScope & typeof globalThis

const firebase: FirebaseOptions = {
  apiKey: import.meta.env.VITE_FCM_CONFIG_API_KEY || '',
  authDomain: import.meta.env.VITE_FCM_CONFIG_AUTH_DOMAIN || '',
  projectId: import.meta.env.VITE_FCM_CONFIG_PROJECT_ID || '',
  storageBucket: import.meta.env.VITE_FCM_CONFIG_STORAGE_BUCKET || '',
  messagingSenderId: import.meta.env.VITE_FCM_CONFIG_MESSAGING_SENDER_ID || '',
  appId: import.meta.env.VITE_FCM_CONFIG_APP_ID || '',
  measurementId: import.meta.env.VITE_FCM_CONFIG_MEASUREMENT_ID || '',
}

const options: ServiceWorkerProviderOptions = {
  namespace: import.meta.env.VITE_APP_NAMESPACE,
  firebase,
}

const instance = new ServiceWorkerProvider(self, options)
instance.boot()

Constructors ​

constructor ​

• new ServiceWorkerProvider(self, options?): ServiceWorkerProvider

Create a new Service Worker Provider instance.

Parameters ​

NameTypeDescription
selfServiceWorkerGlobalScopeThe service worker's global scope
options?ServiceWorkerProviderOptionsThe options to be used by the service worker provider

Returns ​

ServiceWorkerProvider

Defined in ​

src/pwa/worker.ts:145

Accessors ​

off ​

• get off(): any

Exposes the BusService.off method

Returns ​

any

Defined in ​

src/pwa/worker.ts:204


on ​

• get on(): any

Exposes the BusService.on method

Returns ​

any

Defined in ​

src/pwa/worker.ts:197


once ​

• get once(): any

Exposes the BusService.once method

Returns ​

any

Defined in ​

src/pwa/worker.ts:211


self ​

• get self(): ServiceWorkerGlobalScope

The service worker's global scope

Returns ​

ServiceWorkerGlobalScope

Defined in ​

src/pwa/worker.ts:190

Methods ​

await ​

▸ await<K>(event, options?, ...args): Promise<void | (void | void[])[]>

Exposes the BusService.await method

Type parameters ​

NameType
Kextends keyof BusEventCallbackSignatures

Parameters ​

NameType
eventK
optionsBusEventListenOptions
...argsParameters<BusEventCallback<K>>

Returns ​

Promise<void | (void | void[])[]>

Defined in ​

src/pwa/worker.ts:244


boot ​

▸ boot(): void

Boot the service worker provider

Returns ​

void

Defined in ​

src/pwa/worker.ts:255


emit ​

▸ emit<K>(event, options?, ...args): void

Trigger an event

Type parameters ​

NameType
Kextends keyof BusEventCallbackSignatures

Parameters ​

NameTypeDescription
eventKThe name of the event to emit
optionsBusEventListenOptionsThe options for emitting the event
...argsParameters<BusEventCallback<K>>The arguments to pass to the event callback

Returns ​

void

Defined in ​

src/pwa/worker.ts:221


shutdown ​

▸ shutdown(): void

Returns ​

void

Defined in ​

src/pwa/worker.ts:299

Vueprint is a commercial work product released under the MIT License and is provided as-is with no warranty or guarantee of support.