Rewrite to be slightly more readable

Also, try to fix openWindow not working for Safari PWA
This commit is contained in:
Lim Chee Aun 2023-10-01 23:20:48 +08:00
parent a32a264159
commit 8a4ab1bdb9

View file

@ -161,33 +161,22 @@ self.addEventListener('notificationclick', (event) => {
console.log('NOTIFICATION CLICK payload', payload); console.log('NOTIFICATION CLICK payload', payload);
const { badge, body, data, dir, icon, lang, tag, timestamp, title } = payload; const { badge, body, data, dir, icon, lang, tag, timestamp, title } = payload;
const { access_token, notification_type } = data; const { access_token, notification_type } = data;
const actions = new Promise((resolve) => {
event.notification.close();
const url = `/#/notifications?id=${tag}&access_token=${btoa(access_token)}`; const url = `/#/notifications?id=${tag}&access_token=${btoa(access_token)}`;
self.clients
.matchAll({ event.waitUntil(
(async () => {
const clients = await self.clients.matchAll({
type: 'window', type: 'window',
includeUncontrolled: true, includeUncontrolled: true,
}) });
.then((clients) => {
console.log('NOTIFICATION CLICK clients 1', clients); console.log('NOTIFICATION CLICK clients 1', clients);
if (clients.length && 'navigate' in clients[0]) { if (clients.length && 'navigate' in clients[0]) {
console.log('NOTIFICATION CLICK clients 2', clients); console.log('NOTIFICATION CLICK clients 2', clients);
const bestClient = const bestClient =
clients.find( clients.find(
(client) => (client) => client.focused || client.visibilityState === 'visible',
client.focused || client.visibilityState === 'visible',
) || clients[0]; ) || clients[0];
console.log('NOTIFICATION CLICK navigate', url); console.log('NOTIFICATION CLICK navigate', url);
// Check if URL is root / or /notifications
// const clientURL = new URL(bestClient.url);
// if (
// /^#\/?$/.test(clientURL.hash) ||
// /^#\/notifications/i.test(clientURL.hash)
// ) {
// bestClient.navigate(url).then((client) => client?.focus());
// } else {
// User might be on a different page (e.g. composing a post), so don't navigate anywhere else
if (bestClient) { if (bestClient) {
console.log('NOTIFICATION CLICK postMessage', bestClient); console.log('NOTIFICATION CLICK postMessage', bestClient);
bestClient.postMessage?.({ bestClient.postMessage?.({
@ -198,15 +187,14 @@ self.addEventListener('notificationclick', (event) => {
bestClient.focus(); bestClient.focus();
} else { } else {
console.log('NOTIFICATION CLICK openWindow', url); console.log('NOTIFICATION CLICK openWindow', url);
self.clients.openWindow(url); await self.clients.openWindow(url);
} }
// } // }
} else { } else {
console.log('NOTIFICATION CLICK openWindow', url); console.log('NOTIFICATION CLICK openWindow', url);
self.clients.openWindow(url); await self.clients.openWindow(url);
} }
resolve(); await event.notification.close();
}); })(),
}); );
event.waitUntil(actions);
}); });