Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increase Service Worker life time

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);
});
like image 746
YM-91 Avatar asked Mar 14 '23 00:03

YM-91


1 Answers

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.

like image 69
Marco Castelluccio Avatar answered Mar 24 '23 05:03

Marco Castelluccio