Service Worker 安装成功时更新 UI

Update UI when Service Worker installed successfully

看起来 Service Worker 在 worker 上下文中运行并且无权访问 DOM。但是,一旦安装了 Service Worker,我希望我的用户知道该应用程序现在可以离线工作。我该怎么做?

当 Service Worker 在 activated state 时,这是显示 toast 'Content is cached for offline use' 的最佳时机。注册你的 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);
  });
}

测试 @Prototype Chain's 之后,我想使用 named functions 而不是嵌套 anonymous functions 作为事件处理程序,以使代码看起来更符合我的口味,并希望更容易了解 later/for 其他人。

但只是在花了一些时间整理文档之后,我才设法在正确的对象上收听正确的事件。所以在这里分享我的工作示例,希望能将其他人从繁琐的过程中解救出来。

    // 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!');
        }
    }