-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackgroundNotificationServiceWorker.js
More file actions
50 lines (42 loc) · 1.43 KB
/
Copy pathbackgroundNotificationServiceWorker.js
File metadata and controls
50 lines (42 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
self.addEventListener('install', event => {
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', event => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('message', event => {
if (event.data?.type === 'SKIP_WAITING') {
event.waitUntil(self.skipWaiting());
}
});
self.addEventListener('fetch', event => {
if (event.request.method !== 'GET') return;
const requestUrl = new URL(event.request.url);
if (requestUrl.origin !== self.location.origin) return;
if (!isAppAssetRequest(requestUrl)) return;
event.respondWith(fetch(event.request, { cache: 'reload' }));
});
self.addEventListener('notificationclick', event => {
event.notification.close();
event.waitUntil((async () => {
const targetUrl = event.notification?.data?.url || './index.html';
const clients = await self.clients.matchAll({
includeUncontrolled: true,
type: 'window'
});
const existingClient = clients.find(client => client.url === targetUrl) || clients[0];
if (existingClient?.focus) {
return existingClient.focus();
}
if (self.clients.openWindow) {
return self.clients.openWindow(targetUrl);
}
return null;
})());
});
function isAppAssetRequest(url) {
if (url.pathname === '/' || url.pathname.endsWith('/index.html') || url.pathname.endsWith('/cache-bust.json')) {
return true;
}
return /\.(?:css|html|js|json|png|svg|webp|woff2?)$/u.test(url.pathname);
}