-
Notifications
You must be signed in to change notification settings - Fork 9
/
untitled.js
76 lines (69 loc) · 1.77 KB
/
untitled.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
var cacheStorageKey = 'vue-pwa@v1.0.0'
var assetHostPattern = /\/\/(localhost:8080)/
var cacheList = [
'./',
'./index.html'
]
self.addEventListener('install', e => {
e.waitUntil(
caches.open(cacheStorageKey)
.then(cache => cache.addAll(cacheList))
.then(() => self.skipWaiting())
)
})
self.addEventListener('fetch', function(e) {
// if (assetHostPattern.test(e.request.url)) {
e.respondWith(
caches.match(e.request).then(function(response) {
if (response != null) {
return response
}
return fetch(e.request.url)
})
)
// }
})
self.addEventListener('activate', e => {
// delete old deprecated caches.
caches.keys().then(cacheNames => Promise.all(
cacheNames
.map(cacheName => caches.delete(cacheName))
))
e.waitUntil(self.clients.claim())
})
self.addEventListener('push', function(e) {
if (!(self.Notification && self.Notification.permission === 'granted')) {
return
}
var data = {}
if (e.data) {
data = e.data
data.data = {} // url 只能通过 notificationclick 的 e.notification.data 对象传递
data.data.url = data.url
}
console.log(data)
e.waitUntil(self.registration.showNotification(data.title, data))
})
self.addEventListener('notificationclick', function (e) {
console.log(e)
let notification = e.notification
let url = notification.data.url
if (!url) {
return notification.close()
}
e.waitUntil(
clients.matchAll({
type: "window"
})
.then(function (clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == '/' && 'focus' in client)
return client.focus();
}
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
})