服务人员和网页之间的通信

Atl*_*son 5 service-worker

我正在开发一个应用程序,目标是定期向用户发送通知(例如每小时)。我的想法是使用一旦关闭选项卡便可以运行的服务工作者,并继续向用户发送这些通知。该网页必须能够与服务工作者就有关这些通知的特定详细信息,消息应该是什么,应该以什么间隔运行等进行通信。

我无法理解网页如何与现有服务人员通信,是否有办法让我找出打开网页后是否已经在运行注册的服务人员,并在两者之间建立通信。服务人员和网页?

这是我在想的一个模糊的例子:

// Web Application
worker = registerServiceWorker({ scope: '/static/' }).then(registration => {
    // Verify that everything went well
}); 

postMessageToWorker() {
    // Find the existing worker and send him a message
    // I'm guessing I would receive a callback with the desired response here
}

// Service worker
onmessage('start', () => {
    // Start the interval and send the user notifications
}

onmessage('update', () => {
    // Receive info about updates and apply them
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*rco 5

您可以使用navigator.serviceWorker.getRegistration获取现有注册。

您可以使用postMessage API与 Service Worker 通信。ServiceWorker Cookbook上有一个简单的例子。

请注意,当您的页面关闭时,Service Worker 将不会继续运行,它迟早会被杀死。对于您的用例,似乎Web Push API可以工作。ServiceWorker Cookbook上有一些此 API 的示例。