-
Notifications
You must be signed in to change notification settings - Fork 17
/
service-worker.js
81 lines (71 loc) · 2.52 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
80
81
let cacheName = 'pwa-demo-assets';
let assetsfile = [
'/',
'/index.html',
'/manifest.json'
]
self.addEventListener('install', function (e) {
caches.open(cacheName).then(function (cache) {
console.log('sw install');
return cache.addAll(assetsfile);
})
// e.waitUntil(self.skipWaiting());
});
// 更新缓存
self.addEventListener('activate', function (e) {
e.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', (e) => {
if (/\.jpg$|.png$|.js$|.map$/.test(e.request.url) && e.request.url.indexOf('hot-update.js') === -1) {
console.log(e.request.url);
e.respondWith(
caches.match(e.request).then(function (response) {
let requestToCache = e.request.clone();
if (response) {
fetch(requestToCache).then((res) => {
if (res && res.status === 200) {
caches.open(cacheName).then(function (cache) {
cache.delete(requestToCache);
cache.put(requestToCache, res.clone());
});
}
});
return response;
}
return fetch(requestToCache).then((res) => {
if (!res || res.status !== 200) {
return res;
}
var responseToCache = res.clone();
caches.open(cacheName).then(function (cache) {
cache.put(requestToCache, responseToCache);
});
return res;
});
})
);
} else {
console.log(e.request.url)
return fetch(e.request);
}
});
// 监听推送事件 然后显示通知
self.addEventListener('push', function (event) {
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
const title = 'Push Codelab';
const options = {
body: 'Yay it works.',
icon: 'img/48.png',
badge: 'img/48.png'
};
event.waitUntil(self.registration.showNotification(title, options));
});
// 监听通知的点击事件
self.addEventListener('notificationclick', function (event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
event.waitUntil(
clients.openWindow('https://developers.google.com/web/') // eslint-disable-line
);
});