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