我正在开发一个应用程序,其目标是定期(例如每小时)向用户发送通知。
我的想法是使用一个服务工作者,该服务工作者可以在选项卡关闭后运行,并继续向用户发送这些通知。
网页需要能够与 Service Worker 沟通有关这些通知的具体细节、消息应该是什么、运行的时间间隔等等。
我无法理解网页如何与现有的 Service Worker 进行通信,有没有办法让我知道在网页打开后是否已经有一个注册的 Service Worker 在运行,并在 Web 页面之间建立通信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
}
您可以使用navigator.serviceWorker.getRegistration https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/getRegistration获得现有的注册。
您可以使用以下方式与 Service Worker 进行通信发布消息API https://developer.mozilla.org/en-US/docs/Web/API/Client/postMessage。有一个简单的例子ServiceWorker 食谱 https://serviceworke.rs/message-relay.html.
请注意,当您的页面关闭时,Service Worker 将不会继续运行,它迟早会被杀死。
对于您的用例,似乎是网络推送API https://developer.mozilla.org/en-US/docs/Web/API/Push_API会工作。该 API 上有一些示例ServiceWorker 食谱 https://serviceworke.rs/push-simple.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)