iceshrimp-legacy/src/web/app/sw.js

72 lines
1.6 KiB
JavaScript
Raw Normal View History

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