Sharkey/src/client/app/sw.js

70 lines
1.6 KiB
JavaScript
Raw Normal View History

2017-11-20 20:40:09 +02:00
/**
* Service Worker
*/
2017-11-20 22:09:45 +02:00
import composeNotification from './common/scripts/compose-notification';
2018-09-06 18:02:55 +03:00
import { erase } from '../../prelude/array';
2017-11-20 22:09:45 +02:00
2017-11-27 15:00:48 +02:00
// キャッシュするリソース
const cachee = [
'/'
];
2017-11-20 20:40:09 +02:00
// インストールされたとき
2017-11-27 15:00:48 +02:00
self.addEventListener('install', ev => {
2017-11-21 00:06:36 +02:00
console.info('installed');
2017-11-27 15:00:48 +02:00
2017-11-28 08:09:58 +02:00
ev.waitUntil(Promise.all([
self.skipWaiting(), // Force activate
2019-02-05 07:56:33 +02:00
caches.open(_VERSION_).then(cache => cache.addAll(cachee)) // Cache
2017-11-28 08:09:58 +02:00
]));
2017-11-27 15:00:48 +02:00
});
// アクティベートされたとき
self.addEventListener('activate', ev => {
// Clean up old caches
ev.waitUntil(
caches.keys().then(keys => Promise.all(
2019-02-05 07:56:33 +02:00
erase(_VERSION_, keys)
2017-11-27 15:00:48 +02:00
.map(key => caches.delete(key))
))
);
});
// リクエストが発生したとき
self.addEventListener('fetch', ev => {
ev.respondWith(
// キャッシュがあるか確認してあればそれを返す
caches.match(ev.request).then(response =>
response || fetch(ev.request)
)
);
2017-11-20 20:40:09 +02:00
});
// プッシュ通知を受け取ったとき
self.addEventListener('push', ev => {
// クライアント取得
2017-11-21 00:06:36 +02:00
ev.waitUntil(self.clients.matchAll({
2017-11-20 20:40:09 +02:00
includeUncontrolled: true
}).then(clients => {
// クライアントがあったらストリームに接続しているということなので通知しない
if (clients.length != 0) return;
const { type, body } = ev.data.json();
2017-11-21 00:06:36 +02:00
2017-11-20 22:09:45 +02:00
const n = composeNotification(type, body);
2017-11-21 00:06:36 +02:00
return self.registration.showNotification(n.title, {
body: n.body,
icon: n.icon,
});
}));
2017-11-20 20:40:09 +02:00
});
2017-11-28 08:41:41 +02:00
self.addEventListener('message', ev => {
if (ev.data == 'clear') {
caches.keys().then(keys => {
for (const key of keys) caches.delete(key);
});
2017-11-28 08:41:41 +02:00
}
});