How to read Client.postMessage before page loading?

I have a working service that emits Client.postMessage during retrieval when a cached resource changes. I use this to notify the user of an update.

My problem is that when the resource of the active page changes and the worker of the service emits this message, the page is not loaded yet, so javascript cannot receive the message.

Is there a better way to deal with such cases than using waitUntil to pause a few seconds before the message is issued?

+4
source share
1 answer

- IndexedDB , , , message.

ibd-keyval , :

// In your service worker:
importScripts('https://unpkg.com/idb-keyval@2.3.0/idb-keyval.js');

async function notifyOfUpdates(urls) {
  const clients = await self.clients.matchAll();
  for (const client of clients) {
    client.postMessage({
      // Structure your message however you'd like:
      type: 'update',
      urls,
    });
  }

  // Read whatever currently saved in IDB...
  const updatedURLsInIDB = await idb.get('updated-urls') || [];
  // ...append to the end of the list...
  updatedURLsInIDB.push(...urls);
  // ...and write the updated list to IDB.
  await idb.set('updated-urls', updatedURLsInIDB);
}


// In your web page:
<script src="https://unpkg.com/idb-keyval@2.3.0/idb-keyval.js"></script>
<script>
  async listenForUrlUpdates() {
    const updatedURLsInIDB = await idb.get('updated-urls');
    // Do something with updatedURLsInIDB...

    // Clear out the list now that we've read it:
    await idb.delete('updated-urls');

    // Listen for ongoing updates:
    navigator.serviceWorker.addEventListener('message', event => {
      if (event.data.type === 'update') {
        const updatedUrls = event.data.urls;
        // Do something with updatedUrls
      }
    });
  }
</script>
+4

Source: https://habr.com/ru/post/1694322/


All Articles