如何在服务辅助角色中等待'install'事件中的'message'事件?



我有一个场景,我需要在服务工作者的更新事件上将最新版本文件数组的后邮件发送到服务工作者。

当前代码

reg.onupdatefound = function() {
        // The updatefound event implies that reg.installing is set; see
        // https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event
        var installingWorker = reg.installing;
        console.log('on update found');
        // service worker is updated with version name eesh   
        if(reg.installing)
        {
          reg.installing.postMessage({
          data: cacheUrls()
          });
        }

        installingWorker.onstatechange = function() {
          switch (installingWorker.state) {
            case 'installed':
              if (navigator.serviceWorker.controller) {
                // At this point, the old content will have been purged and the fresh content will
                // have been added to the cache.
                // It's the perfect time to display a "New content is available; please refresh."
                // message in the page's interface.
                console.log('New or updated content is available. yo yo');
                // navigator.serviceWorker.controller.postMessage({data: location})  
              } else {
                // At this point, everything has been precached.
                // It's the perfect time to display a "Content is cached for offline use." message.
                console.log('ServiceWorker registration successful with scope: ', reg.scope);
              }
              break;
            case 'redundant':
              console.error('The installing service worker became redundant.');
              break;
          }
        };
      };
};

,但有时安装首先发生,然后在服务工作者中侦听"消息"事件。我如何等待"安装"服务工作者内部的"消息"事件?

我相信您可以做这样的事情:

// sw.js
self.addEventListener('install', function(e) {
    const installPromise = new Promise(function(resolve, reject) {
        // do install stuff, like caching resources, etc.
        self.addEventListener('message', function(e) {
            // 1. do something with the received data
            // 2. remove this event listener
            resolve();
        });
    });
    e.waitUntil(installPromise);
});

e.waitUntil()接受Promise,因此我们给它一个。install阶段仅在将承诺传递给e.waitUntil()解决方案时才能完成。我们仅在收到客户端的消息后才解决Promise

最新更新