后台可以很好的接收消息,但是前台的人接收不到消息,只显示“后台已更新本网站”。
我使用了 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/