Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communcation between service worker and web page

I'm working on an application where the goal is sending the user a notification at a regular interval (every hour for example). My idea was to use a service worker that could be running once the tab has been closed and keep on sending the user these notifications. The web page needs to be able to communicate with the service worker about specific details about these notifications, what the message should be, at what interval it should be running and such.

I'm having trouble understanding how the web page is able to communicate with the existing service worker, is there a way for me to find out if I already have a registered service worker running once the web page is opened and set up communication between the service worker and the web page?

Here's a vague example of what I'm thinking:

// 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
}
like image 283
Atli Guðlaugsson Avatar asked Feb 24 '16 16:02

Atli Guðlaugsson


1 Answers

You can use navigator.serviceWorker.getRegistration to get an existing registration.

You can communicate with the service worker using the postMessage API. There's a simple example on the ServiceWorker Cookbook.

Notice that the service worker will not keep running when your page has been closed, sooner or later it will be killed. For your use case, seems like the Web Push API would work. There are a few examples of this API on the ServiceWorker Cookbook.

like image 200
Marco Castelluccio Avatar answered Oct 18 '22 21:10

Marco Castelluccio