[w3c/ServiceWorker] Using BroadcastChannel to wake up a service worker (#975)

While a service worker can currently subscribe to a BroadcastChannel to receive messages from it, it will only receive messages as long as some other event keeps the service worker alive. It would be useful if it was possible for a BroadcastChannel to wake up a service worker.

Maybe something like this:
```js
// sw.js
registration.subscribeToBroadcastChannel('foo');

addEventListener('onbroadcastchannelmessage', e => {
  console.log('Received message from channel: ' + e.source.name);
});
```

Not sure what the API should look like though:

- Attach channel subscriptions to the registration or to the specific worker?
- If attached to the worker, specify fixed list of subscriptions once (on install event), or allow subscribing/unsubscribing later?
- Reuse existing onmessage event, or add new event (and if new event, what/where)?
- Events should probably be `ExtendableMessagEvent`. But how will the event handler know what channel a message was send over? Could set `.source` to a `BroadcastChannel` instance, but will that instance then also get all messages to the channel?

Or rather than inventing new API surface and events, we could just record all channels the SW subscribed to after first-run similar to how we record all the events the SW subscribed to. Then we'd rely on the SW script re-subscribing to the same channels whenever it is woken up. So the following would "just work":
```js
// sw.js
const channel = new BroadcastChannel('foo');
channel.onmessage = e => { console.log('Received message', e.data); };

// or even
new BroadcastChannel('foo').onmessage = e => console.log(e.data);
```

In some sense not having extra API seems cleaner, but it's also kind of magic, and we'd have to decide when to record what channels the worker is actually subscribed to... Thoughts?

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/ServiceWorker/issues/975

Received on Thursday, 8 September 2016 19:33:29 UTC