簡體   English   中英

Firebase Cloud Messaging Service Worker和self.addEventListener的問題

[英]Issue with Firebase Cloud Messaging Service Worker and self.addEventListener

我已經為我的Web應用程序成功構建了FCM通知服務工作程序,到目前為止,它的工作正常。 我曾經用過敬酒來在Web應用程序中呈現通知。 當前未打開網站時,服務工作者當前遇到問題。 這是我來自firebae-messaging-sw.js的代碼:

//Firebase initialized above here
messaging.setBackgroundMessageHandler(function (payload) {
const notiTitle = payload.data.title;
var body = payload.data.body;

const opts = {
    icon : "/ui/img/icons/android-chrome-256x256.png",
    actions : [
        {
            action: 'view-ticket',
            title: 'View Ticket',
            icon: null
        }
    ],
    body: body
    //url: link
};
self.addEventListener('notificationclick', function (event) {
    const clickedNotification = event.notification;
    clickedNotification.close();

    if(!event.action) {
        return;
    }

    switch(event.action) {
        case 'view-ticket':
            var promiseChain = clients.openWindow(payload.data.link);
            break;
    }

    event.waitUntil(promiseChain);

});
return self.registration.showNotification(notiTitle, opts);

});

除了一個問題,它幾乎可以完美運行。 當我發送第一個測試通知時, payload.data.link被解析為OK。 但是在下一個通知中, payload.data.link不會更新,因此發送了錯誤的鏈接。 認為 self.addEventListener可能self.addEventListener在錯誤的位置,但是我不確定該如何放置它(在return之后我顯然不能這樣做)。

知道在哪里放置事件偵聽器代碼嗎?

我修好了它! 我能夠通過添加一個變量並將addEventListener移到setBackgroundMessageHandler外部來修復此問題,如下所示:

//Firebase started up above
var clickDestination; //init this variable

//add event listener before background message handler and use clickDestination
self.addEventListener('notificationclick', function (event) {
const clickedNotification = event.notification;
clickedNotification.close();
if (!event.action) {
    return;
}

if(event.action === 'view-ticket') {
    var promise = new Promise(function () {
        return clients.openWindow(clickDestination);
    });
    event.waitUntil(promise);
}


});


messaging.setBackgroundMessageHandler(function (payload) {
const notiTitle = payload.data.title;
var body = payload.data.body;
clickDestination = payload.data.link; //set clickDestination based on payload
/*self.addEventListener('notificationclick', function (event) {
    event.notification.close();
    event.waitUntil(self.clients.openWindow(payload.data.link));
});*/

const opts = {
    icon : "/ui/img/icons/android-chrome-256x256.png",
    actions : [
        {
            action: 'view-ticket',
            title: 'View Ticket',
            icon: '/ui/img/icons/ticket-icon.png'
        }
    ],
    body: body
};


return self.registration.showNotification(notiTitle, opts);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM