2017-08-29 1 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()は、我々はそれを1つずつ与えるのでPromiseを受け入れます。 installフェーズは、約束がe.waitUntil()に渡されたときにのみ完了します。私たちはクライアントからのメッセージを既に受け取ったばかりの場合にのみPromiseを解決します。

関連する問題