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?
I still do not know why it does not work, but I used this code on the server:
const channel = new BroadcastChannel('sw-messages');
channel.postMessage(payload.data);
And this code on the client instead:
const channel = new BroadcastChannel('sw-messages');
channel.addEventListener('message', event => {
console.log('Received:', event.data);
});
It works well.