在我的
firebase-messaging-sw.js
中无法查看除安装、激活或推送之外的任何事件。正在接收和提供通知,但我无法看到 notificationclick 的事件处理程序。当我收到来自 Firebase 的通知并被单击时,我无法在服务工作人员日志中看到发生的 notificationclick 事件。
我正在使用 @nuxtjs/firebase 8.2.2 并按照指南中的设置进行操作:https://firebase.nuxtjs.org/service-options/messaging.html.
在 firebase-messaging-sw.js 中
self.addEventListener('notificationclick', function (event) {
console.log('Notification click');
event.notification.close();
const url = 'home';
event.waitUntil(
self.clients.matchAll({ type: 'window' }).then((windowClients) => {
// Check if there is already a window/tab open with the target URL
for (let i = 0; i < windowClients.length; i++) {
const client = windowClients[i];
// If so, just focus it.
if (client.url === url && 'focus' in client) {
console.log('focusing..');
return client.focus();
}
}
if (self.clients.openWindow) {
console.log('open window');
}
})
);
}, false);
我还尝试在单独的页面上对我们的服务人员使用
postMessage()
将用户电子邮件注入到服务人员:
在账户.vue中
navigator.serviceWorker.ready.then((sw) => {
console.log('Requesting permission. Service worker: ', sw);
Notification.requestPermission().then(async (permission) => {
let token = null;
if (permission === 'granted') {
console.log('Notification permission granted.');
await sw.active.postMessage({ action: 'saveEmail', email: this.email });
}
});
});
在 firebase-messaging-sw.js 中
self.addEventListener('message', async (msg) => {
console.log('message', msg);
const clients = await self.clients.matchAll({ type: 'window' });
for (const client of clients) {
client.postMessage(msg);
}
if (msg.data.action === 'saveEmail') {
USER_EMAIL = msg.data.email;
}
});
TLDR;我无法看到我的
notificationclick
中发生的 firebase-messaging-sw.js
事件。
编辑:我添加了正在被击中的
push
事件处理程序,但我仍然无法捕获 notificationclick
事件
所以我从我在 firebase-messaging-sw.js 中使用的 importScripts 中找到了这一点:
export async function onNotificationClick(
event: NotificationEvent
): Promise<void> {
const internalPayload: MessagePayloadInternal =
event.notification?.data?.[FCM_MSG];
if (!internalPayload) {
return;
} else if (event.action) {
// User clicked on an action button. This will allow developers to act on action button clicks
// by using a custom onNotificationClick listener that they define.
return;
}
// Prevent other listeners from receiving the event
event.stopImmediatePropagation();
event.notification.close();
具体来说,
event.stopImmediatePropagation();
阻止我自己的通知单击侦听器接收事件。通过将我自己的 notificationclick 侦听器放在 importScripts 之上可以解决此问题。
关于
postMessage
,由于与另一个正在运行的服务人员通信而失败。我使用 getRegistrations()
来指定要与哪个 Service Worker 通信。
navigator.serviceWorker.getRegistration('service-worker-scope-url').then((registration) => {
console.log('we found our sw!');
if (registration) {
registration.active.postMessage({ action: 'saveEmail', email: this.$auth.user.email });
}
});