Service Worker安装成功后更新UI

时间:2016-06-07 23:24:44

标签: javascript service-worker progressive-web-apps

看起来Service Worker在工作者上下文中运行,并且无法访问DOM。但是,一旦安装了Service Worker,我希望我的用户知道应用程序现在可以脱机工作。我怎么能这样做?

2 个答案:

答案 0 :(得分:6)

当服务工作者在map时,这是展示吐司的最佳时间' activated state'。注册服务人员时,请尝试以下代码。

Content is cached for offline use

答案 1 :(得分:1)

在对@Prototype Chain answer above进行测试后,我想使用named functions而非嵌套anonymous functions作为事件处理程序,以使代码更加令人愉悦为了我的口味,希望以后更容易理解/为他人。

但是只有花了一些时间对文档进行排序,我才能设法在正确的对象上听取正确的事件。所以在这里分享我的工作实例,希望能让其他人免于繁琐的过程。

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