How to get instance created of Serviceworker with "custom-service-worker.js"



  • Hello everyone!

    I am trying to push notification with serviceworker of PWA in quasar.

    In quasar.conf.js, I set workboxPluginMode: ‘InjectManifest’ :
    d31b33ea-0c82-4cf3-9746-e603993012a1-image.png

    So, As I understand it. When i build with command: “quasar build -m pwa” then service worker will be created by code in my “custom-service-worker.js” file.
    You can read here : https://quasar.dev/quasar-cli/developing-pwa/configuring-pwa#Service-Worker

    My problem is : When I try subscribe to server with function:

    function subscribeUser() {
      
      self.registration.pushManager.subscribe({
          userVisibleOnly: true,
          applicationServerKey: applicationServerKey
        })
        .then(function (subscription) {
          console.log('User is subscribed.');
    
          updateSubscriptionOnServer(subscription);
    
          isSubscribed = true;
        })
        .catch(function (err) {
          console.log('Failed to subscribe the user: ', err);
        });
    }
    // I write this code in "register-service-worker.js"
    

    I have error , because my instance service worker have status active is null so it cannot subscribe.

    How to catch event instance created of service worker ( with status is : activated ) in this way.

    Note: In another way, when I do not config workboxPluginMode: ‘InjectManifest’ :. So I can catch event instance created of service worker in ready() function of “register-service-worker.js” file

    Thanks you.



  • [Option 1]
    Here is my workerServices.js

    let worker = null
    
    export const initWorkerInstance = () => {
      console.log('worker is not initialized')
      return new Promise(resolve => {
        if ('navigator' in window && 'serviceWorker' in window.navigator) {
          const { serviceWorker } = window.navigator
    
          return serviceWorker.ready.then((workerInstance) => {
            worker = workerInstance
            resolve(worker)
          })
        }
        return resolve(null)
      })
    }
    
    export const getWorkerInstance = () => {
      return new Promise(resolve => {
        if (worker === null) return initWorkerInstance().then(resolve)
        return resolve(worker)
      })
    }
    

    then in components you use

    import { getWorkerInstance } from 'workerServices.js'
    
    getWorkerInstance().then(workerInstance => {
       this.worker = workerInstance.active
    })
    

    [Option 2]: I highly recommend you use this library https://github.com/webpack-contrib/worker-loader


Log in to reply