与 Angular.js 控制器通信 service-worker

Dav*_*que 3 javascript events push-notification angularjs service-worker

我正在我的应用程序中实现推送通知。我做了一个 service-worker 来在我的浏览器(Chrome)中显示通知。

现在,我需要调用一个位于 Angular Controller 中的函数。我试图在我的服务工作者中制作这样的事件。

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;
    });
  })
 );
});
Run Code Online (Sandbox Code Playgroud)

在此事件中,我处理通知并尝试使用事件。

在控制器中我写了下面的代码

document.addEventListener('myEvent', function(){
 console.log("im here");
});
Run Code Online (Sandbox Code Playgroud)

但是浏览器没有显示 console.log()

有完成这项任务的想法吗?非常感谢!

Lin*_*ham 5

这是我为 Angular(或窗口/文档端的任何东西)与 Service Worker 之间的通信所做的工作


在你的 angular 应用程序中的某个地方。

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.
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的服务工作者开始时

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;  
  }
});
Run Code Online (Sandbox Code Playgroud)

当您收到一份 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;
    });
  })
 );
});
Run Code Online (Sandbox Code Playgroud)