简体   繁体   中英

Firebase messaging service worker click handler doesn't work

I am using FCM to handle push notifications, but notification is coming in data key instead of notification .

Here is the code I am using to handle new message and show as notification. I am seeing notification with all options and data as I specified. However, when I click notification, it doesn't fire any "notificationclick" event. It also doesn't print 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 you can check with your firebase-messaging-sw.js file in the application whether the recent changes are in that file after the build.

2 we only need the most recent changes in firebase-messaging-sw.js, so need to check and most recent updated firebase-messaging-sw.js file and unregister all older firebase-messaging-sw.js.

it worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM