-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
79 lines (72 loc) · 2.42 KB
/
Copy pathsw.js
File metadata and controls
79 lines (72 loc) · 2.42 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Daystack Service Worker (sw.js)
*
* WHY IS THIS HERE?
* Modern mobile browsers (specifically Chrome on Android) have strict security rules:
* 1. They block standard browser-based notifications (new Notification()).
* 2. They require a Service Worker (reg.showNotification()) to display any notification.
* 3. They block Service Workers registered from 'blob:' or 'data:' URLs.
*
* To support native background notifications on mobile while maintaining the app's
* minimalist philosophy, this physical sw.js file is required in the root directory.
*/
const CACHE_NAME = 'daystack-v2';
const ASSETS = [
'./',
'./index.html',
'./manifest.json',
'./icon.png',
'./icon-192.png',
'./icon-512.png'
];
self.addEventListener('install', (event) => {
self.skipWaiting();
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS))
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then(keys => {
return Promise.all(
keys.filter(key => key !== CACHE_NAME).map(key => caches.delete(key))
);
}).then(() => clients.claim())
);
});
self.addEventListener('fetch', (event) => {
if (event.request.method !== 'GET') return;
event.respondWith(
caches.open(CACHE_NAME).then(cache => {
return cache.match(event.request).then(cachedResponse => {
// Fetch from network in the background to keep the cache fresh
const fetchPromise = fetch(event.request).then(networkResponse => {
if (networkResponse && networkResponse.status === 200 && networkResponse.type === 'basic') {
cache.put(event.request, networkResponse.clone());
}
return networkResponse;
}).catch(() => {
// Ignore network errors when fully offline
});
// Return cached response instantly if available, otherwise wait for the network
return cachedResponse || fetchPromise;
});
})
);
});
self.addEventListener('notificationclick', function(event) {
event.notification.close();
event.waitUntil(
clients.matchAll({ type: 'window', includeUncontrolled: true }).then(windowClients => {
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
if ('focus' in client) {
return client.focus();
}
}
if (clients.openWindow) {
return clients.openWindow(self.registration.scope);
}
})
);
});