increase Service Worker life time

做~自己de王妃 提交于 2019-12-10 22:06:00

问题


I'm trying push notifications using service workers. use my own server to send notifications and eventSource is used to establish the connection. after i open the webpage service worker is running perfectly. but it stops after few seconds. what i want is to run service worker without getting stopped. i want it to run until the browser is opened. can anyone recommend a way to do that. ?

this is my 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);
});

回答1:


Service workers are meant to have a short lifetime, you can't make them run forever.

You could use a shared worker to do that, but they only run if your website is open.

You are trying to mix the push API and EventSource. If you use the Push API, you don't need to keep the service worker alive all the time, you can just make it execute when a push notification arrives.

See the example on the ServiceWorker Cookbook.




回答2:


This is not possible and it's not the purpose of a service-worker. Why exactly do you want to keep it alive ?




回答3:


When you catch a push like here:

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

the first thing to do is to use event.waitUntil() who takes a promise and extends the lifetime of the event and the serviceworker

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


来源:https://stackoverflow.com/questions/35837967/increase-service-worker-life-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!