navigator.serviceWorker.controller 在页面刷新之前为空

问题描述 投票:0回答:2

我使用 AngularJS 并使用 Service Worker 来接收推送通知。
但是直到页面刷新

navigator.serviceWorker.controller
都是
null
,我不知道如何解决这个问题。

serviceworker的一些代码:

self.addEventListener('push', pwServiceWorker.pushReceived);
self.addEventListener('notificationclick', pwServiceWorker.notificationClicked);

// refresh caches
self.addEventListener('activate', function(event) {
    event.waitUntil(
        caches.keys().then(function(cacheNames) {
            return Promise.all(
                cacheNames.map(function(cacheName) {
                    return caches.delete(cacheName);
                })
            );
        })
    );
});

收到推送后,在 serviceworker 中向客户端发送消息:

self.clients.matchAll().then(function(all) {
    console.log(all);
    all.forEach(function(client) {
        client.postMessage(data);
    });
});

在 mainController.js 中给出如下消息:

if (!navigator.serviceWorker || !navigator.serviceWorker.register) {
    console.log("This browser doesn't support service workers");
    return;
}

// Listen to messages from service workers.
navigator.serviceWorker.addEventListener('message', function(event) {
    console.log("Got reply from service worker: " + event.data);
});

// Are we being controlled?
if (navigator.serviceWorker.controller) {
    // Yes, send our controller a message.
    console.log("Sending 'hi' to controller");
    navigator.serviceWorker.controller.postMessage("hi");
} else {
    // No, register a service worker to control pages like us.
    // Note that it won't control this instance of this page, it only takes effect
    // for pages in its scope loaded *after* it's installed.
    navigator.serviceWorker.register("service-worker.js")
        .then(function(registration) {
            console.log("Service worker registered, scope: " + registration.scope);
            console.log("Refresh the page to talk to it.");
            // If we want to, we might do `location.reload();` so that we'd be controlled by it
        })
        .catch(function(error) {
            console.log("Service worker registration failed: " + error.message);
        });
}
javascript service-worker
2个回答
41
投票

这是预期的行为。要控制所有打开的页面而不等待刷新/重新打开,您必须将这些命令添加到 Service Worker 中:

self.addEventListener('install', function(event) {
    event.waitUntil(self.skipWaiting()); // Activate worker immediately
});

self.addEventListener('activate', function(event) {
    event.waitUntil(self.clients.claim()); // Become available to all pages
});

您可以在 skipWaiting() 文档和 clients.claim() 文档中阅读有关它们的更多信息。


4
投票

确保您的 Service Worker 的范围包含有问题的 url。

© www.soinside.com 2019 - 2024. All rights reserved.