2017-08-29 52 views
1

我有一個場景,我需要發送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; 
      } 
     }; 
     }; 
}; 

但有時會發生安裝,然後再「消息」事件在服務人員聽。我如何等待服務人員的「安裝」事件中的'消息'事件?

回答

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所以我們給它一個。只有在傳遞給e.waitUntil()的承諾解決時,install階段纔會完成。一旦我們收到來自客戶端的消息,我們只解決Promise