How can I claim a client when initializing a ServiceWorker to prevent having to reload the page?

后端 未结 1 894
醉话见心
醉话见心 2021-01-25 09:19

I\'m having trouble to wrap my head around the Clients.claim API of the ServiceWorker. From what I understand (here and here) I can call claim() on the service work

相关标签:
1条回答
  • 2021-01-25 09:56

    Firstly, you are seem to be getting the error because of a typo in your code. See notes about it at the bottom.

    Besides, skipWaiting() and Clients.claim() does both install and activate new SW with a single request. But quite naturally you will only get static assets like css after you reload.

    So, even when equipped with skipWaiting() and Clients.claim(), you need two page reloads to see updated static content like new html or styles;

    Page load #1

    • Request to sw.js is made, and since SW contents is changed install event is fired on it.
    • Also activate event is fired, since you have self.skipWaiting() in your install handler.
    • Consequently, your activate handler run and there is your self.clients.claim() call. Which will order the SW to take over the control of all the clients which under control of it's predecessor.
    • At this point, assets in cache are updated and your pages are all controlled by new service worker. Any Ajax request in range of service worker will return newly cached responses, for example.

    Page load #2

    Your app loads, and your SW responds from cache by hijacking the requests as usual. But now caches are up-to-date, and user gets to use app completely with new assets.

    The error you are getting

    Uncaught (in promise) TypeError: Illegal invocation error must be due to a missing a parenthesis in your activate handler;

      event.waitUntil(self.clients.claim()
        .then(caches.keys)
        .then(function(cache_name_list) {
          return Promise.all(
            cache_name_list.map(function() {...}
          ); <-- Here is our very lonely single parenthesis.
        })
      );
    

    That error should go away if you fix it.

    0 讨论(0)
提交回复
热议问题