How: ServiceWorker check if ready to update

流过昼夜 提交于 2020-01-13 07:33:17

问题


What I am trying to achieve:

  • render page with loader/spinner

  • if service-worker.js is registered and active, then check for updates

    • if no updates, then remove loader
    • if updatefound and new version installed, then reload the page
  • else register service-worker.js
    • when updatefound, meaning new one was installed, remove loader

I am using sw-precache module for me to generate service-worker.js and following registration code:

window.addEventListener('load', function() {

  // show loader
  addLoader();

  navigator.serviceWorker.register('service-worker.js')
    .then(function(swRegistration) {

      // react to changes in `service-worker.js`
      swRegistration.onupdatefound = function() {
        var installingWorker = swRegistration.installing;
        installingWorker.onstatechange = function() {
          if(installingWorker.state === 'installed' && navigator.serviceWorker.controller){

            // updated content installed
            window.location.reload();
          } else if (installingWorker.state === 'installed'){

            // new sw registered and content cached
            removeLoader();
          }
        };
      }

      if(swRegistration.active){
        // here I know that `service-worker.js` was already installed
        // but not sure it there are changes
        // If there are no changes it is the last thing I can check
        // AFAIK no events are fired afterwards
      }

    })
    .catch(function(e) {
      console.error('Error during service worker registration:', e);
    });
});

After reading the spec it is clear that there are no handlers for something like updatenotfound. Looks like serviceWorker.register checks if service-worker.js changed internally by running get-newest-worker-algorithm, but I cannot see similar methods exposed via public api.

I think my options are:

  • wait for couple of seconds after service worker registration becomes active to see if onupdatefound is fired
  • fire custom events from service-worker.js code if cache was not updated

Any other suggestions?


Edit:

I've came up with some code which solves this issue by using postMessage() between SW registration and SW client (as @pate suggested)

Following demo tries to achieve checks through postMessage between SW client and SW registration, but fails as SW code is already cached DEMO


Edit:

So by now it looks like I cannot implement what I want because:

  1. when service worker is active you cannot check for updates by evaluating some code in SW - this is still the same cached SW, no changes there
  2. you need to wait for onupdatefound, there is nothing else that will notify of changes in SW
  3. activation of older SW comes before onupdatefound
  4. if there is no change, nothing fires after activation
  5. SW registration update() is immature, keeps changing, Starting with Chrome 46, update() returns a promise that resolves with 'undefined' if the operation completed successfully or there was no update
  6. setting timeout to postpone view rendering is suboptimal as there is no clear answer to how long should it be set to, it depends on SW size as well

回答1:


The other answer, provided by Fabio, doesn't work. The Service Worker script has no access to the DOM. It's not possible to remove anything from the DOM or, for instance, manipulate any data that is handling DOM elements from inside the Service Worker. That script runs separately with no shared state.

What you can do, though, is send messages between the actual page-running JS and the Service Worker. I'm not sure if this is the best possible way to do what the OP is asking but can be used to achieve it.

  1. Register an onmessage handler on the page
  2. Send a message from the SW's activate or install event to the page
  3. Act accordingly when the message is received on the page

I have myself kept SW version number in a variable inside the SW. My SW has then posted that version number to the page and the page has stored it into the localStorage of the browser. The next time the page is loaded SW posts it current version number to the page and the onmessage handler compares it to the currently stored version number. If they are not the same, then the SW has been updated to some version number that was included in the mssage. After that I've updated the localStorage copy of the version number and done this and that.

This flow could also be done in the other way around: send a message from the page to the SW and let SW answer something back, then act accordingly.

I hope I was able to explain my thoughts clearly :)




回答2:


The only way that pops up in my mind is to start the loader normally and then remove it in the service-worker, in the install function. I will give this a try, in your service-worker.js:

self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    }).then(function() {
        ***removeLoader();***
        return self.skipWaiting();
    })
  );
});


来源:https://stackoverflow.com/questions/45759595/how-serviceworker-check-if-ready-to-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!