service worker 不会跳过等待状态

service worker doesn't skip waiting state

为了掌握service workers,我还在做实验,我遇到了一个问题,可能是因为我在JavaScript和service worker方面缺乏专业知识。

当我希望新服务人员使用 postMessage() skipWaiting() 时出现问题。如果我显示一个带有按钮的弹出窗口并在那里绑定对 postMessage() 的调用,一切正常。如果我直接调用 postMessage() 是行不通的。这是一个竞争条件,因为 SOMETIMES 它有效,但我无法识别竞争条件。

顺便说一句,postMessage() 调用有效,服务工作者正在记录收到消息时应记录的内容:

// Listen to messages from clients.
self.addEventListener('message', event => {
    switch(event.data) {
        case 'skipWaiting': self.skipWaiting(); console.log('I skipped waiting... EXTRA');
            break;
    }
}); 

这是代码。重要的一点是 if (registration.waiting) 条件。未注释的代码有效,注释的代码无效:

// Register service worker.
if ('serviceWorker' in navigator) {
    // Helpers to show and hide the update toast.
    let hideUpdateToast = () => {
        document.getElementById('update_available').style.visibility = 'hidden';
    };

    let showUpdateToast = (serviceworker) => {
        document.getElementById('update_available').style.visibility = 'visible';
        document.getElementById('force_install').onclick = () => {
            serviceworker.postMessage('skipWaiting');
            hideUpdateToast();
        };
        document.getElementById('close').onclick = () => hideUpdateToast();
    };

    window.addEventListener('load', () => {

        let refreshing = false;
        navigator.serviceWorker.addEventListener('controllerchange', () => {
            if (refreshing) return;
            refreshing = true;
            window.location.reload();
        });

        navigator.serviceWorker.register('/sw.js').then(registration => {
            // A new service worker has been fetched, watch for state changes.
            //
            // This event is fired EVERY TIME a service worker is fetched and
            // succesfully parsed and goes into 'installing' state. This
            // happens, too, the very first time the page is visited, the very
            // first time a service worker is fetched for this page, when the
            // page doesn't have a controller, but in that case there's no new
            // version available and the notification must not appear.
            //
            // So, if the page doesn't have a controller, no notification shown.
            registration.addEventListener('updatefound', () => {
                // return;  // FIXME
                registration.installing.onstatechange = function () {  // No arrow function because 'this' is needed.
                    if (this.state == 'installed') {
                        if (!navigator.serviceWorker.controller) {
                            console.log('First install for this service worker.');
                        } else {
                            console.log('New service worker is ready to activate.');
                            showUpdateToast(this);
                        }
                    }
                };
            });

            // If a service worker is in 'waiting' state, then maybe the user
            // dismissed the notification when the service worker was in the
            // 'installing' state or maybe the 'updatefound' event was fired
            // before it could be listened, or something like that. Anyway, in
            // that case the notification has to be shown again.
            //
            if (registration.waiting) {
                console.log('New service worker is waiting.');
                // showUpdateToast(registration.waiting);

                // The above works, but this DOESN'T WORK.
                registration.waiting.postMessage('skipWaiting');
            }

        }).catch(error => {
            console.log('Service worker registration failed!');
            console.log(error);
        });
    });
}

为什么使用按钮 onclick 事件的间接调用有效,而调用 postMessage() 却无效?

我完全不知所措,我敢打赌答案很简单,只是我太瞎了,看不到它。

非常感谢。

看起来像是 Chromium 或 WebKit 中的错误,因为此代码在 Firefox 中始终有效,但在 Chrome 和 Edge 中大部分时间都失败了。

我已经向 Chromium 报告了该错误,让我们看看它是错误还是我的代码很奇怪。我已经设法构建了仍然重现问题的最小代码,它非常小,可以在错误报告中找到。

可以找到报告here

抱歉打扰了,我会继续调查这个问题,但无论我如何尝试,代码仍然时不时地失败,我无法在我的代码中发现竞争条件。