为什么我在客户端上没有收到 client.postMessage ?
我的服务工作人员中有此代码:
messaging.onBackgroundMessage(function (payload) {
console.log("onBackgroundMessage email and contact_link:");
console.log(payload.data.email,payload.data.contact_link);
self.clients.matchAll().then(clients => {
clients.forEach(client => client.postMessage({
msg: "This is a message from the SW",
email: payload.data.email,
contact_link: payload.data.contact_link
}));
})
});
我在客户端上有此代码:
navigator.serviceWorker.addEventListener('message', payload => {
console.log("Message from ServiceWorker");
console.log(payload.data.msg, payload.data.email, payload.data.contact_link);
});
我从服务工作人员的控制台上正确获取了数据,但是客户端的控制台显示所有数据均未定义。 为什么会这样,我做错了什么?
I have this code in my service worker:
messaging.onBackgroundMessage(function (payload) {
console.log("onBackgroundMessage email and contact_link:");
console.log(payload.data.email,payload.data.contact_link);
self.clients.matchAll().then(clients => {
clients.forEach(client => client.postMessage({
msg: "This is a message from the SW",
email: payload.data.email,
contact_link: payload.data.contact_link
}));
})
});
I have this code on the client:
navigator.serviceWorker.addEventListener('message', payload => {
console.log("Message from ServiceWorker");
console.log(payload.data.msg, payload.data.email, payload.data.contact_link);
});
I get the data properly on the console from the service worker, however the client's console says all the data is undefined.
Why is that, what am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我仍然不知道为什么它不起作用,但我在服务器上使用了这段代码:
而在客户端上使用了这段代码:
它运行良好。
I still do not know why it does not work, but I used this code on the server:
And this code on the client instead:
It works well.
默认情况下,client.postMessage() 方法仅将消息发送到由 Service Worker 控制的客户端(页面)。
您可以修改clients.matchAll()以包含不受控制的客户端:
The client.postMessage() method by default only send messages to clients (pages) that are controlled by the service worker.
You can modify clients.matchAll() to include uncontrolled clients: