Re: [ServiceWorker] Workers & SharedWorkers within ServiceWorkers (#678)

For the [Mozilla email case](slightlyoff/BackgroundSync#70), I am hoping this sort of relationship would work:

```javascript
// in service worker that handles background sync notifications
self.onsync = function(event) {
  if (event.registration.id === "periodicSync") {
    event.waitUntil(new Promise(resolve, reject) {
      // This worker connects to the email servers and syncs data to IDB.
      var emailWorker = new SharedWorker("email-worker.js");

      // Listen for a message from the worker to know when it is done
      // with its sync work.
      emailWorker.port.onmessage = function(e) {
        var data = e.data;
        if (data.type === 'syncComplete') {
          // Shared worker complete. Resolve the waitUntil
          // promise to allow this service worker to be
          // shut down. If no other documents or workers
          // have a reference to email-worker.js, then the
          // shared worker would be shut down. If there
          // are other documents/workers with a reference
          // to email-worker.js would keep the shared worker
          // alive. 
          resolve();
        }
      };

      // Start communicating with the worker, ask it to sync.
      // Wait to be messaged back to resolve the waitUntil
      // promise.
      emailWorker.port.start();
      emailWorker.port.postMessage({
        type: 'sync'
      });
    });
  }
};
```

Just a sketch, things like errors not handled here, and in the email case, we could have multiple accounts on different sync intervals, so probably be a bit more complicated than this sketch, but I was hoping this sort of thing would be possible.


---
Reply to this email directly or view it on GitHub:
https://github.com/slightlyoff/ServiceWorker/issues/678#issuecomment-92992257

Received on Tuesday, 14 April 2015 17:40:11 UTC