当我的网页在后台(窗口最小化,或其他标签)时,我无法接收推送消息,它只显示通知,这是正常的,但我的page.js没有任何反应尝试发回帖子。
sw.js:
messaging.setBackgroundMessageHandler(function (payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
const title = '¡Mensaje Nuevo!';
const options = {
body: 'conductor: ' + payload.data.chofer_id + ' - ' + payload.data.mensaje,
icon: '/icono.png',
};
send_message_to_all_clients('sound');
return self.registration.showNotification(title, options);
});
function send_message_to_all_clients(msg) {
clients.matchAll().then(clients => {
clients.forEach(client => {
send_message_to_client(client, msg).then(m => console.log("SW Received Message: " + m));
})
})
}
function send_message_to_client(client, msg) {
return new Promise(function (resolve, reject) {
var msg_chan = new MessageChannel();
msg_chan.port1.onmessage = function (event) {
if (event.data.error) {
reject(event.data.error);
} else {
resolve(event.data);
}
};
client.postMessage("SW Says: '" + msg + "'", [msg_chan.port2]);
});
}
page.js
// Handler for messages coming from the service worker
navigator.serviceWorker.addEventListener('message', function (event) {
console.log("Client 1 Received Message: " + event.data);
$.playSound('Sounds/Tethys.mp3');
});
当我发送消息并且我在网页上时,控制台日志显示并播放声音:
客户端1收到消息:[对象对象]
但永远不会在后台。
请有人帮忙,已经很长时间了。
答案 0 :(得分:0)
最后我发现了我的问题!
我正在发送带有通知部分的FCM消息,并且阻止使用服务工作者功能将消息发回我的页面。
{
"to": "<token>",
"notification": { // this was the problem
"body": "test"
}
"data": {
"chofer_id": 3,
"mensaje": "hola"
}
}