Web应用程序显示“此网站已在后台更新”

时间:2018-07-20 11:26:58

标签: html firebase firebase-cloud-messaging service-worker pwa

可以很好地在后台接收该消息,但是前围的人会收到该消息,并仅显示“此网站已在后台更新”。

我使用了fcm文档中的代码示例。

Index.html(跳过了初始化脚本)

messaging.onMessage(function(payload) {
   console.log('Message received. ', payload);
   notificationTitle = payload.data.title;
   notificationOptions = {
     body: payload.data.body,
     icon: payload.data.icon
   };

   var notification = new Notification(notificationTitle,notificationOptions); });

sw.js

messaging.setBackgroundMessageHandler(function(payload) {

  const notificationTitle = payload.data.title;
  const notificationOptions = {
    body: payload.data.body,
    icon: payload.data.icon,
    badge: payload.data.badge
  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});

有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:1)

如果要在应用程序中显示来自服务人员的消息,请使用以下内容。

在您的sw.js中,这是您与用户/应用实例进行对话的方式:

self.clients.matchAll().then(function(clients) {
    clients.forEach(function(client) {
        client.postMessage({
            msg: "cached: " + event.request.url
        });
    });
});   

然后在index.html脚本中,这就是您处理消息的方式:

if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
        navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
            console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
            console.log('ServiceWorker registration failed: ', err);
        });
    });
}
navigator.serviceWorker.addEventListener('message', function(event) {
  console.log("service worker " + event.data.msg);
  //you can do whatever you want now that you have this data in script.
});