YM-91
YM-91

Reputation: 311

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);
});

Upvotes: 4

Views: 3537

Answers (3)

lellefood
lellefood

Reputation: 2096

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>)
}

Upvotes: 2

Marco Castelluccio
Marco Castelluccio

Reputation: 10802

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.

Upvotes: 7

Mathieu Le Bihan
Mathieu Le Bihan

Reputation: 53

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

Upvotes: 0

Related Questions