2017-11-20 19:40:09 +01:00
|
|
|
/**
|
|
|
|
* Service Worker
|
|
|
|
*/
|
2020-05-23 06:19:31 +02:00
|
|
|
declare var self: ServiceWorkerGlobalScope;
|
2017-11-20 19:40:09 +01:00
|
|
|
|
2020-12-26 06:11:08 +01:00
|
|
|
import composeNotification from '@/sw/compose-notification';
|
2017-11-27 14:00:48 +01:00
|
|
|
|
2019-09-26 22:12:56 +02:00
|
|
|
const version = _VERSION_;
|
|
|
|
const cacheName = `mk-cache-${version}`;
|
|
|
|
|
|
|
|
const apiUrl = `${location.origin}/api/`;
|
|
|
|
|
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
|
|
|
|
2020-05-23 06:19:31 +02:00
|
|
|
ev.waitUntil(
|
2019-09-26 22:12:56 +02:00
|
|
|
caches.open(cacheName)
|
|
|
|
.then(cache => {
|
|
|
|
return cache.addAll([
|
2020-02-09 04:47:50 +01:00
|
|
|
`/?v=${version}`
|
2019-09-26 22:12:56 +02:00
|
|
|
]);
|
|
|
|
})
|
|
|
|
.then(() => self.skipWaiting())
|
2020-05-23 06:19:31 +02:00
|
|
|
);
|
2019-09-26 22:12:56 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
self.addEventListener('activate', ev => {
|
|
|
|
ev.waitUntil(
|
|
|
|
caches.keys()
|
|
|
|
.then(cacheNames => Promise.all(
|
|
|
|
cacheNames
|
|
|
|
.filter((v) => v !== cacheName)
|
|
|
|
.map(name => caches.delete(name))
|
|
|
|
))
|
|
|
|
.then(() => self.clients.claim())
|
|
|
|
);
|
|
|
|
});
|
|
|
|
|
|
|
|
self.addEventListener('fetch', ev => {
|
|
|
|
if (ev.request.method !== 'GET' || ev.request.url.startsWith(apiUrl)) return;
|
|
|
|
ev.respondWith(
|
|
|
|
caches.match(ev.request)
|
|
|
|
.then(response => {
|
|
|
|
return response || fetch(ev.request);
|
|
|
|
})
|
|
|
|
.catch(() => {
|
2020-02-09 04:47:50 +01:00
|
|
|
return caches.match(`/?v=${version}`);
|
2019-09-26 22:12:56 +02:00
|
|
|
})
|
|
|
|
);
|
2017-11-27 14:00:48 +01:00
|
|
|
});
|
|
|
|
|
2017-11-20 19:40:09 +01:00
|
|
|
// プッシュ通知を受け取ったとき
|
|
|
|
self.addEventListener('push', ev => {
|
|
|
|
// クライアント取得
|
2017-11-20 23:06:36 +01:00
|
|
|
ev.waitUntil(self.clients.matchAll({
|
2017-11-20 19:40:09 +01:00
|
|
|
includeUncontrolled: true
|
2020-05-23 06:19:31 +02:00
|
|
|
}).then(async clients => {
|
2017-11-20 19:40:09 +01:00
|
|
|
// クライアントがあったらストリームに接続しているということなので通知しない
|
|
|
|
if (clients.length != 0) return;
|
|
|
|
|
|
|
|
const { type, body } = ev.data.json();
|
2017-11-20 23:06:36 +01:00
|
|
|
|
2020-05-23 06:19:31 +02:00
|
|
|
return self.registration.showNotification(...(await composeNotification(type, body)));
|
2017-11-20 23:06:36 +01:00
|
|
|
}));
|
2017-11-20 19:40:09 +01:00
|
|
|
});
|