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

前端之家收集整理的这篇文章主要介绍了javascript – navigator.serviceWorker.controller在页面刷新之前为空前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用 angularjs并使用服务工作者接收推送通知.
但navigator.serviceWorker.controller在页面刷新之前为空,我不知道如何解决这个问题

一些维修工作者的代码

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

解决方法

这是预期的行为.要在不等待刷新/重新打开的情况下控制所有打开的页面,您必须将这些命令添加到服务工作者:
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() docs和clients.claim() docs中阅读有关它们的更多信息.

猜你在找的JavaScript相关文章