增加服务人员的生活时间

时间:2016-03-07 07:04:34

标签: javascript push-notification addeventlistener server-sent-events service-worker

我正在尝试使用服务工作者推送通知。 使用我自己的服务器发送通知,eventSource用于建立连接。 打开网页后,服务工作人员运行得很好。但它在几秒钟后停止。 我想要的是运行服务工作者而不停止。我希望它一直运行,直到浏览器打开。谁能推荐一种方法来做到这一点。 ?

这是我的ServiceWorker JS

/**
 * 
 */
'use strict';
var eventSource2 = new EventSource("Servlet");
console.log('Started', eventSource2);
eventSource2.addEventListener('install', function(event) {
    eventSource2.skipWaiting();
    console.log('Installed', event);

});

eventSource2.addEventListener('push',function(event) {
                    console.log(event.data);
                    var title = event.data;
                    self.registration.showNotification(title,{
                                        'body' : event.data,
                                        'icon' : 'http://icons.iconarchive.com/icons/designbolts/free-multimedia/1024/iMac-icon.png',
                                        'tag' : 'click',
                                    });
                    console.log("data from down", event.data);
                });

eventSource2.addEventListener('activate', function(event){
    console.log('Activated', event);
});

eventSource2.addEventListener('fetch', function(event) {
    console.log('Push message', event);
});

3 个答案:

答案 0 :(得分:6)

服务工作者的生命周期短,你不能让他们永远活着。

您可以使用共享工作人员执行此操作,但只有在您的网站处于打开状态时才会运行。

您正在尝试混合推送API和EventSource。如果您使用Push API,则不需要让服务工作者始终保持活动状态,您可以在推送通知到达时执行它。

请参阅example on the ServiceWorker Cookbook

答案 1 :(得分:0)

这是不可能的,这不是服务工作者的目的。为什么你想让它保持活力?

答案 2 :(得分:0)

当你像这里一样推动时:

self.addEventListener('push',function(event) {

要做的第一件事就是使用承诺的event.waitUntil()并延长事件和服务工作者的生命周期

self.addEventListener('push',function(event) {
  event.waitUntil(<YOUR PROMISE>)
}