如何在服务工作者的'install'事件中等待'message'事件?

时间:2017-08-29 10:51:32

标签: service-worker

我有一个场景,我需要在服务工作者的更新事件中将postMessage的最新版本文件数组从客户端发送到服务工作者。

当前代码

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;
          }
        };
      };
};

但有时安装首先发生,然后在服务工作者中监听“message”事件。我如何在服务工作者的'install'事件中等待'message'事件?

1 个答案:

答案 0 :(得分:1)

我相信你可以这样做:

// 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