我已经实现了一个 service worker,可以在我的应用程序上完全提供网络推送通知。
但是,我在隐身模式下使用 firefox 时发现了一个错误。
在 MacOS 上,我可以退出“主”窗口(不是隐身模式),但可以继续在另一个隐身窗口中工作。
这样做时,我的服务人员不断收到导致显示通知的“推送”事件。
当我点击通知时,没有任何反应,因为我对 self.clients.openWindow() 的调用抛出了一个错误,因为当前服务工作者没有可见的窗口。
我想在显示通知之前检测此配置,要么不显示通知,要么附加有关情况的明确消息。
这是我的“notificationclick”处理程序:
self.addEventListener('notificationclick', async (event) => {
const {
data: {
community: {
id: communityId,
},
project: {
code: projectCode,
},
news: {
id: newsId,
},
},
} = event.notification.data;
const commentId = event.notification.data.data?.comment?.id;
const url = `https://${self.location.hostname}/project/${projectCode}/community/${communityId}/news/${newsId}?referrer=pushBrowser${commentId ? `&commentId=${commentId}` : ''}`;
// eslint-disable-next-line no-param-reassign
gNotificationsStatus.set(event.notification.tag, { clicked: true });
event.notification.close(); // Android needs explicit close.
event.waitUntil((async () => {
await logEvent(
EVENTS.NOTIF_CLICKED,
computeNotifEventPayload(event.notification.data, EVENT_DESTINATION.AMPLITUDE),
computeNotifEventPayload(event.notification.data, EVENT_DESTINATION.MS),
);
console.log('checking opened tabs');
const windowClients = await self.clients.matchAll({ type: 'window' });
// Check if there is already a window/tab open with the target URL
for (let i = 0; i < windowClients.length; i += 1) {
const client = windowClients[i];
// If so, just focus it.
if (client.url === url
&& 'focus' in client) {
client.focus();
}
}
// If not, then open the target URL in a new window/tab.
console.log('opening window to', url);
if (self.clients.openWindow) {
try {
const client = await self.clients.openWindow(url);
client.focus();
} catch (err) {
console.log(err);
}
}
})());
});
我在谷歌浏览器上测试过,它可以打开窗口
Safari遇到和firefox一样的问题