ServiceWorkerContainer.ready for a specific scriptURL?

后端 未结 1 1595
鱼传尺愫
鱼传尺愫 2021-01-25 01:16

ServiceWorkerContainer.ready resolves to an active ServiceWorkerRegistration, but if there are multiple service workers in play (e.g. service workers from previous page loads, m

相关标签:
1条回答
  • 2021-01-25 01:56

    First, notice there can be only one active service worker per scope and your client page can be controlled by at most one and only one service worker. So, when ready resolves, you know for sure the service worker controlling your page is active.

    To know if an arbitrary sw is active you can register it and check the queue of service workers in the registration and listen for changes in their state. For instance:

    function registerReady(swScript, options) {
      return navigator.serviceWorker.register(swScript, options)
      .then(reg => {
        // If there is an active worker and nothing incoming, we are done.
        var incomingSw = reg.installing || reg.waiting;
        if (reg.active && !incomingSw) {
          return Promise.resolve();
        }
    
        // If not, wait for the newest service worker to become activated.
        return new Promise(fulfill => {
          incomingSw.onstatechange = evt => {
            if (evt.target.state === 'activated') {
              incomingSw.onstatechange = null;
              return fulfill();
            }
          };
        });
      })
    }
    

    Hope it makes sense to you.

    0 讨论(0)
提交回复
热议问题