javascript - Firebase 消息传递服务工作人员点击处理程序不起作用

标签 javascript firebase firebase-cloud-messaging service-worker web-push

我正在使用 FCM 处理推送通知,但通知即将到来 data键而不是 notification .

这是我用来处理新消息并显示为通知的代码。
我看到了我指定的所有选项和数据的通知。但是,当我单击通知时,它不会触发任何“notificationclick”事件。它也不打印event.notification .

importScripts('https://www.gstatic.com/firebasejs/5.3.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.3.1/firebase-messaging.js');


firebase.initializeApp({
    messagingSenderId: "SOME_ID",
});

const messaging = firebase.messaging();


messaging.setBackgroundMessageHandler(payload => {
    console.log(payload);
    const options = {
        body: payload.data.body,
        icon: payload.data.icon,
        click_action: payload.data.click_action,
        link: payload.data.link,
        data: {
            time: new Date(Date.now()).toString(),
            click_action: payload.data.click_action,
        },
    };

    self.registration.showNotification(payload.data.title, options);

});



self.addEventListener("notificationclick", function(event) {
    console.log(event.notification);
    const clickedNotification = event.notification;
    clickedNotification.close();

    const urlToOpen = clickedNotification.data && clickedNotification.data.click_action;

    const promiseChain =  clients.matchAll({
        type: 'window',
        includeUncontrolled: true,
    })
        .then((windowClients) => {
            let matchingClient = null;

            for (let i = 0; i < windowClients.length; i++) {
                const windowClient = windowClients[i];
                if (windowClient.url === urlToOpen) {
                    matchingClient = windowClient;
                    break;
                }
            }

            if (matchingClient) {
                return matchingClient.focus();
            } else {
                return clients.openWindow(urlToOpen);
            }
        });

    event.waitUntil(promiseChain);

});

最佳答案

1 您可以使用应用程序中的 firebase-messaging-sw.js 文件检查构建后该文件中是否存在最近的更改。

2 我们只需要 firebase-messaging-sw.js 中的最新更改,因此需要检查最新更新的 firebase-messaging-sw.js 文件并取消注册所有旧的 firebase-messaging-sw.js。

它对我有用。

关于javascript - Firebase 消息传递服务工作人员点击处理程序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51835775/

相关文章:

javascript - 谁能告诉我如何使用addClass和removeClass实际上我的代码不起作用

java - 来自 Java 而不是 Firebase 控制台的 Firebase 云消息传递通知

firebase - Firebase 函数 SignOut 返回 true - Flutter

android - 所有 firebase 库必须高于或低于 14.0.0

android - Firebase 推送通知发送两次

android - 接收 Firebase 通知不规律

javascript - 在 http 和 https 之间共享 dom 存储

javascript - 为什么设置 "No license field": true in your package. json 时 "private"警告消失

javascript - 如何禁用 jQuery-UI 按钮集中的一个按钮?

ios - 使用 Firebase ios 获取数据