简体   繁体   中英

Update UI when Service Worker installed successfully

Looks like Service Worker runs in a worker context and has no access to the DOM. However, once Service Worker installed, I want my users to know that the app will now work offline. How can I do that?

When the Service Worker is in activated state , this is the perfect time to display the toast ' Content is cached for offline use '. Try something below code while registering your service worker.

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js').then(function(reg) {
    // updatefound is fired if service-worker.js changes.
    reg.onupdatefound = function() {
      var installingWorker = reg.installing;

      installingWorker.onstatechange = function() {
        switch (installingWorker.state) {
          case 'installed':
            if (navigator.serviceWorker.controller) {
              // At this point, the old content will have been purged and the fresh content will
              // have been added to the cache.
              // It's the perfect time to display a "New content is available; please refresh."
              // message in the page's interface.
              console.log('New or updated content is available.');
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a "Content is cached for offline use." message.
              console.log('Content is now available offline!');
            }
            break;

          case 'redundant':
            console.error('The installing service worker became redundant.');
            break;
        }
      };
    };
  }).catch(function(e) {
    console.error('Error during service worker registration:', e);
  });
}

After testing @Prototype Chain 's answer above , I wanted to use named functions as opposed to nested anonymous functions as event handlers to make code more pleasant to look at for my taste, and hopefully easier to understand later/for others.

But only after spending some time sorting docs, I managed to listen correct events on correct objects. So sharing my working example here in hopes of saving someone else from tedious process.

    // make sure that Service Workers are supported.
    if (navigator.serviceWorker) {
        navigator.serviceWorker.register('/sw.js')
            .then(function (registration) {
                console.log("ServiceWorker registered");

                // updatefound event is fired if sw.js changed
                registration.onupdatefound = swUpdated;
            }).catch(function (e) {
            console.log("Failed to register ServiceWorker", e);
        })
    }

    function swUpdated(e) {
        console.log('swUpdated');
        // get the SW which being installed
        var sw = e.target.installing;
        // listen for installation stage changes
        sw.onstatechange = swInstallationStateChanged;
    }

    function swInstallationStateChanged(e) {
        // get the SW which being installed
        var sw = e.target;
        console.log('swInstallationStateChanged: ' + sw.state);

        if (sw.state == 'installed') {
            // is any sw already installed? This function will run 'before' 'SW's activate' handler, so we are checking for any previous sw, not this one.
            if (navigator.serviceWorker.controller) {
                console.log('Content has updated!');
            } else {
                console.log('Content is now available offline!');
            }
        }

        if (sw.state == 'activated') {
            // new|updated SW is now activated.
            console.log('SW is activated!');
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM