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,52 +161,40 @@ 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) => { const url = `/#/notifications?id=${tag}&access_token=${btoa(access_token)}`;
event.notification.close();
const url = `/#/notifications?id=${tag}&access_token=${btoa(access_token)}`; event.waitUntil(
self.clients (async () => {
.matchAll({ 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.focused || client.visibilityState === 'visible',
(client) => ) || clients[0];
client.focused || client.visibilityState === 'visible', console.log('NOTIFICATION CLICK navigate', url);
) || clients[0]; if (bestClient) {
console.log('NOTIFICATION CLICK navigate', url); console.log('NOTIFICATION CLICK postMessage', bestClient);
// Check if URL is root / or /notifications bestClient.postMessage?.({
// const clientURL = new URL(bestClient.url); type: 'notification',
// if ( id: tag,
// /^#\/?$/.test(clientURL.hash) || accessToken: access_token,
// /^#\/notifications/i.test(clientURL.hash) });
// ) { bestClient.focus();
// 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) {
console.log('NOTIFICATION CLICK postMessage', bestClient);
bestClient.postMessage?.({
type: 'notification',
id: tag,
accessToken: access_token,
});
bestClient.focus();
} else {
console.log('NOTIFICATION CLICK openWindow', url);
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(); // }
}); } else {
}); console.log('NOTIFICATION CLICK openWindow', url);
event.waitUntil(actions); await self.clients.openWindow(url);
}
await event.notification.close();
})(),
);
}); });