Workbox: Consider a `postMessage` plugin as an alternative to `BroadcastChannel`

Created on 21 Feb 2018  路  4Comments  路  Source: GoogleChrome/workbox

Library Affected:
workbox-build, workbox-sw

Browser & Platform:
Any besides Chrome, FF

Issue or Feature Request Description:
Hi!

Workbox has been fantastic. I have been working on an Edge-specific project using the MS Edge Windows Insiders builds. These builds do _not_ support the BroadcastChannel API that FF and Chrome use.

Instead, one can communicate with the Host page via postMessage. Also, @angular/service-worker uses postMessage as a built-in. We decided against @angular/service-worker for the configurability of workbox, but bumped into this in our transition.

It'd be great to have workbox have a default plugin that enables various postMessage communications by default. That way, we can have Cache update (via 'staleWhileRevalidate') notifications go to host page, without having to write our own plugin.

Others may benefit from this as well.

Thanks!

Documentation Feature Request

All 4 comments

We can consider it. In the meantime, if you want equivalent functionality, you can add your own cacheDidUpdate plugin to your handler:

const postMessagePlugin = {
  cacheDidUpdate: async ({cacheName, url, oldResponse, newResponse}) => {
    // Use whatever logic you want to determine whether the responses differ.
    if (oldResponse && (oldResponse.headers.get('etag') !== newResponse.headers.get('etag'))) {
      const clients = await self.clients.matchAll();
      for (const client of clients) {
        // Use whatever message body makes the most sense.
        // Note that `Response` objects can't be serialized.
        client.postMessage({url, cacheName});
      }
    }
  },
};

Great! Thank you!!

Jeff it would be good to add this to WebFundamentals somewhere. Maybe under "advanced recipes" or we could create a "custom plugins" page. What do you think?

I'm going to close this now that we have the recipe merged in our docs.

If there's strong demand to update the "official" workbox-broadcast-cache-update plugin to add support for postMessage(), then we can reconsider.

Was this page helpful?
0 / 5 - 0 ratings