Firebase 云消息服务工作者和 self.addEventListener 的问题
2018-04-10
1605
我已成功为我的 Web 应用构建了 FCM 通知服务工作线程,到目前为止运行正常。我使用 toastr 在 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
解析正常。但在下一个通知中,
payload.data.link
未更新,因此发送了错误的链接。我
认为
也许
self.addEventListener
放错了地方,但我不确定还能怎样放置它(显然在
return
之后我无法这样做)。
知道我应该把事件监听器代码放在哪里吗?
1个回答
我修复了它!我可以通过添加变量并将
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);
Dominic Kirby
2018-04-10