html - 显示 "This website has been updated in the background"的网络应用程序

标签 html firebase firebase-cloud-messaging service-worker progressive-web-apps

后台可以很好的接收消息,但是前台的人接收不到消息,只显示“后台已更新本网站”。

我使用了 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);
});

有人可以帮忙吗?谢谢!

最佳答案

如果您想在您的应用中显示来自 service worker 的消息,请使用以下命令。

在您的 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.
});

关于html - 显示 "This website has been updated in the background"的网络应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51441510/

相关文章:

firebase - 使用自定义域名作为 firebase 数据库/身份验证/存储 URL

google-chrome - 如何在 Chrome 中实现 Google Cloud Messaging - 主题消息传递?

android - 卸载并重新安装应用程序会导致重复的推送消息 firebase

jquery - 窗口滚动时执行多项功能

html - 模糊线性渐变背景到纯色 CSS

javascript - 包含垂直可滚动 div 的水平可滚动 div 在 iOS 上不会水平滚动

ios - Apple Mach-O 链接器错误 _OBJC_CLASS_$_FIRInstanceID

javascript - 用于聊天应用程序或私有(private)应用程序的 Firebase 数据结构

android - 添加firebase_messaging插件后,Gradle构建失败

html - 滚动覆盖 div 而不滚动整个页面