简体   繁体   English

成功安装Service Worker后更新UI

[英]Update UI when Service Worker installed successfully

Looks like Service Worker runs in a worker context and has no access to the DOM. 看起来Service Worker在工作程序上下文中运行,并且无法访问DOM。 However, once Service Worker installed, I want my users to know that the app will now work offline. 但是,一旦安装了Service Worker,我希望我的用户知道该应用程序现在可以脱机工作。 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 '. 当Service Worker处于activated state ,这是显示吐司“ 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. 在测试完@Prototype Chain答案之后 ,我想使用named functions (而不是嵌套的anonymous functions作为事件处理程序,以使代码看起来更令人愉悦,并希望以后更容易理解。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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