Search code examples
javascriptprogressive-web-appsworkbox

How can I tell Workbox to check for a new version (long after page is loaded)


I have a complex app that runs fine offline and syncs when it comes back online. The only thing that does not "sync" is the app itself.

I know how to get a message when a new version is "installed" but I do not know how to tell Workbox to check for an update. I want the equivalent of:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(function(registration) {
    // registration worked
    console.log('Registration succeeded.');
    button.onclick = function() {
      registration.update(); // <=== THIS WITH Workbox
    }
  }).catch(function(error) {
    // registration failed
    console.log('Registration failed with ' + error);
  });
};

[edit] Found this on github https://github.com/GoogleChrome/workbox/blob/master/packages/workbox-window/src/Workbox.ts#L193

But the TypeScript types are not in sync as of August 2019.

// Very recent change in Workbox
await wb.update()

// Or
const reg = wb.register()
// ...
reg.update()

Solution

  • Workbox does not have a feature for checking updates once the page is loaded. How ever you may manually trigger the check for update as below.

    navigator.serviceWorker.register('/sw.js').then(reg => {
      setInterval(function () {
        reg.update();
      },<intervalInMilliseconds>);
    });
    

    With Workbox

    You can use the recently introduced update method. But you still need to use setInterval and call update function.