-
Notifications
You must be signed in to change notification settings - Fork 11
/
sw.js
45 lines (43 loc) · 1.28 KB
/
sw.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
/* eslint-env serviceworker */
self.addEventListener('install', function (event) {
self.skipWaiting()
sendMessage(event, 'render')
})
self.addEventListener('activate', function (event) {
sendMessage(event, 'render')
})
self.addEventListener('sync', function (event) {
sendMessage(event, 'render')
self.registration.showNotification(event.tag)
})
self.onmessage = function (e) {
if (e.data === 'ping') {
sendMessage(e, 'Message sent from the service worker')
} else {
self.registration.showNotification(e.data)
}
}
self.addEventListener('fetch', function (event) {
event.respondWith(caches.match(event.request).then(function (cachedResponse) {
if (cachedResponse) return cachedResponse
// Use the preloaded response, if it's there
else return event.preloadResponse
}).then(function (response) {
if (response) return response
// Else try the network.
return fetch(event.request) /* global fetch */
}))
})
function sendMessage (e, msg) {
if (e.source && typeof e.source.postMessage === 'function') {
e.source.postMessage(msg)
} else if (self.clients) {
clients.matchAll().then(function (clients) {
for (var client of clients) {
client.postMessage(msg)
}
})
} else if (e.data.port) {
e.data.port.postMessage(msg)
}
}