David Luque
David Luque

Reputation: 1108

To communicate service-worker with Angular.js controller

I'm implementing Push Notifications in my app. I made a service-worker to show the notification in my browser (Chrome).

Now, I need to call a function that it's inside an Angular Controller. I was trying to make an event like this in my service worker.

self.addEventListener('push', function(event) {
 event.waitUntil(
  fetch(self.CONTENT_URL, {headers: headers})
  .then(function(response) {
    if (response.status !== 200) {

    }
    return response.json().then(function(data) {

      /* some stuff*/

      document.dispatchEvent('myEvent');

      return notification;
    });
  })
 );
});

In this event I handle the notification and I'm trying to use an event.

In the controller I wrote the code below

document.addEventListener('myEvent', function(){
 console.log("im here");
});

But the browser doesn't show the console.log()

Any ideas to complete this task? Thanks a lot!

Upvotes: 3

Views: 3565

Answers (1)

Linh Pham
Linh Pham

Reputation: 3025

Here is what I did for communications between angular (or anything at the window/document side) with Service Worker


Somewhere in your angular app.

if ('serviceWorker' in navigator) {

  // ensure service worker is ready
  navigator.serviceWorker.ready.then(function (reg) {

    // PING to service worker, later we will use this ping to identifies our client.
    navigator.serviceWorker.controller.postMessage("ping");

    // listening for messages from service worker
    navigator.serviceWorker.addEventListener('message', function (event) {
      var messageFromSW = event.data;
      console.log("message from SW: " + messageFromSW);
      // you can also send a stringified JSON and then do a JSON.parse() here.
    });
  }
}

At the start of your service worker

let angularClient;
self.addEventListener('message', event => {
  // if message is a "ping" string, 
  // we store the client sent the message into angularClient variable
  if (event.data == "ping") { 
    angularClient = event.source;  
  }
});

When you receive a push

// In your push stuff
self.addEventListener('push', function(event) {
 event.waitUntil(
  fetch(self.CONTENT_URL, {headers: headers})
  .then(function(response) {
    if (response.status !== 200) {

    }
    return response.json().then(function(data) {

      /* some stuff*/

      angularClient.postMessage('{"data": "you can send a stringified JSON here then parse it on the client"}');

      return notification;
    });
  })
 );
});

Upvotes: 6

Related Questions