Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get and show push data from serviceworker in chrome

I use pushwoosh for receive push notification in my web app. every things working well and received push message in serviceworker listener but I want give push messge data from serviceworker and process it in another js class

main.js like this:

if ('serviceWorker' in navigator) {
  console.log('Service Worker is supported');
  navigator.serviceWorker.register('sw.js').then(function() {
    return navigator.serviceWorker.ready;
  }).then(function(reg) {
    console.log('Service Worker is ready :^)', reg);
      // TODO
  }).catch(function(error) {
    console.log('Service Worker error :^(', error);
  });
}

// get push message data in main.js and process it

service worker like this :

self.addEventListener('push', function(event) {
  console.log('Push message', event);

  var title = 'Push message';

  event.waitUntil(
    self.registration.showNotification(title, {
      'body': 'The Message',
      'icon': 'images/icon.png'
    }));
});
like image 413
Reza Mazarlou Avatar asked Jul 02 '16 05:07

Reza Mazarlou


1 Answers

As I mentioned in a comment, this seems a slightly odd use-case for a service worker rather than a standard worker, but:

You can have your service worker send a message to all connected clients when it gets a message pushed to it.

This answer shows a complete example of a service worker talking to clients, but fundamentally:

  1. The pages it manages listen for messages:

    navigator.serviceWorker.addEventListener('message', event => {
        // use `event.data`
    });
    
  2. The service worker sends to them like this:

    self.clients.matchAll().then(all => all.forEach(client => {
        client.postMessage(/*...message here...*/);
    }));
    

Or with ES5 and earlier syntax (but I don't think any browser supporting service workers doesn't also support arrow functions):

Page listening:

navigator.serviceWorker.addEventListener('message', function(event) {
    // use `event.data`
});

Worker sending:

self.clients.matchAll().then(function(all) {
    all.forEach(function(client) {
        client.postMessage(/*...message here...*/);
    });
});
like image 86
T.J. Crowder Avatar answered Sep 23 '22 17:09

T.J. Crowder