【问题标题】:FCM web background service workerFCM Web 后台服务工作者
【发布时间】:2017-11-02 02:18:30
【问题描述】:

当我的网页在后台(窗口最小化或其他标签)时,我无法接收推送消息,它只显示可以的通知,但是当我的 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 收到消息:[object Object]

但从不在后台。

请有人帮忙,已经好几个月了。

【问题讨论】:

    标签: javascript firebase firebase-cloud-messaging service-worker


    【解决方案1】:

    我终于找到了我的问题!

    我正在发送带有通知部分的 FCM 消息,它阻止了使用 service worker 功能将消息发布回我的页面。

    {
      "to": "<token>",
     "notification": { // this was the problem
        "body": "test"
      }
      "data": {
        "chofer_id": 3,
        "mensaje": "hola"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-06
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      相关资源
      最近更新 更多