-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
79 lines (69 loc) · 2.8 KB
/
service-worker.js
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
const CACHE_NAME = 'offline'
const OFFLINE_URL = './pages/offline.html'
window.self.addEventListener('install', function (event) {
console.log('[ServiceWorker] Install')
event.waitUntil((async () => {
const cache = await window.self.caches.open(CACHE_NAME)
// Setting {cache: 'reload'} in the new request will ensure that the response
// isn't fulfilled from the HTTP cache; i.e., it will be from the network.
await cache.add(new Request(OFFLINE_URL, { cache: 'reload' }))
// await cache.add(OFFLINE_URL)
await cache.add('./img/dino-nobg.png')
await cache.add('./img/maskable_icon_x384.png')
})())
window.self.skipWaiting()
})
window.self.addEventListener('activate', (event) => {
console.log('[ServiceWorker] Activate')
event.waitUntil((async () => {
// Enable navigation preload if it's supported.
// See https://developers.google.com/web/updates/2017/02/navigation-preload
if ('navigationPreload' in window.self.registration) {
await window.self.registration.navigationPreload.enable()
}
})())
// Tell the active service worker to take control of the page immediately.
window.self.clients.claim()
})
window.self.addEventListener('fetch', function (event) {
// console.log('[Service Worker] Fetch', event.request.url);
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
const preloadResponse = await event.preloadResponse
if (preloadResponse) {
return preloadResponse
}
const networkResponse = await fetch(event.request)
return networkResponse
} catch (error) {
console.log('[Service Worker] Fetch failed; returning offline page instead.', error)
const cache = await window.self.caches.open(CACHE_NAME)
const cachedResponse = await cache.match(OFFLINE_URL)
return cachedResponse
}
})())
}
})
// function notifyMe () {
// if (!('Notification' in window)) {
// // Check if the browser supports notifications
// alert('This browser does not support desktop notification')
// } else if (Notification.permission === 'granted') {
// // Check whether notification permissions have already been granted;
// // if so, create a notification
// const notification = new Notification('Hi there!')
// // …
// } else if (Notification.permission !== 'denied') {
// // We need to ask the user for permission
// Notification.requestPermission().then((permission) => {
// // If the user accepts, let's create a notification
// if (permission === 'granted') {
// const notification = new Notification('Hi there!')
// // …
// }
// })
// }
// // At last, if the user has denied notifications, and you
// // want to be respectful there is no need to bother them anymore.
// }