【问题标题】:Communcation between service worker and web pageService Worker 和网页之间的通信
【发布时间】:2016-06-07 01:29:39
【问题描述】:

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

我无法理解网页如何与现有的服务人员进行通信,有没有办法让我在打开和设置网页后确定我是否已经有一个注册的服务人员在运行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
}

【问题讨论】:

    标签: service-worker


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多