2020-05-09 19:28:18 +03:00
|
|
|
---
|
|
|
|
layout: compress
|
2021-01-25 01:20:51 +03:00
|
|
|
# PWA service worker
|
2020-05-09 19:28:18 +03:00
|
|
|
---
|
|
|
|
|
2021-04-10 09:51:04 +03:00
|
|
|
self.importScripts('{{ "/assets/js/data/swcache.js" | relative_url }}');
|
2020-05-09 19:28:18 +03:00
|
|
|
|
2021-04-10 09:51:04 +03:00
|
|
|
const cacheName = 'chirpy-{{ "now" | date: "%Y%m%d.%H%M" }}';
|
|
|
|
|
|
|
|
function verifyDomain(url) {
|
|
|
|
for (const domain of allowedDomains) {
|
|
|
|
const regex = RegExp(`^http(s)?:\/\/${domain}\/`);
|
|
|
|
if (regex.test(url)) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
2020-05-09 19:28:18 +03:00
|
|
|
|
2020-05-11 20:01:12 +03:00
|
|
|
function isExcluded(url) {
|
2021-04-10 09:51:04 +03:00
|
|
|
for (const item of denyUrls) {
|
|
|
|
if (url === item) {
|
2020-05-11 20:01:12 +03:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2021-04-10 09:51:04 +03:00
|
|
|
self.addEventListener('install', e => {
|
2020-05-09 19:28:18 +03:00
|
|
|
self.skipWaiting();
|
|
|
|
e.waitUntil(
|
2021-04-10 09:51:04 +03:00
|
|
|
caches.open(cacheName).then(cache => {
|
|
|
|
return cache.addAll(resource);
|
2020-05-09 19:28:18 +03:00
|
|
|
})
|
|
|
|
);
|
|
|
|
});
|
|
|
|
|
2021-04-10 09:51:04 +03:00
|
|
|
self.addEventListener('fetch', e => {
|
2020-05-09 19:28:18 +03:00
|
|
|
e.respondWith(
|
2021-04-10 09:51:04 +03:00
|
|
|
caches.match(e.request).then(r => {
|
2021-03-21 10:55:04 +03:00
|
|
|
/* console.log(`[sw] method: ${e.request.method}, fetching: ${e.request.url}`); */
|
2021-04-10 09:51:04 +03:00
|
|
|
return r || fetch(e.request).then(response => {
|
|
|
|
const url = e.request.url;
|
|
|
|
|
|
|
|
if (e.request.method !== 'GET'
|
|
|
|
|| !verifyDomain(url)
|
|
|
|
|| isExcluded(url)) {
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
|
|
|
return caches.open(cacheName).then(cache => {
|
|
|
|
/* console.log('[sw] Caching new resource: ' + e.request.url); */
|
|
|
|
cache.put(e.request, response.clone());
|
2020-05-09 19:28:18 +03:00
|
|
|
return response;
|
|
|
|
});
|
2021-03-21 10:55:04 +03:00
|
|
|
|
2020-05-09 19:28:18 +03:00
|
|
|
});
|
|
|
|
})
|
|
|
|
);
|
|
|
|
});
|
|
|
|
|
2021-04-10 09:51:04 +03:00
|
|
|
self.addEventListener('activate', e => {
|
2020-05-09 19:28:18 +03:00
|
|
|
e.waitUntil(
|
2021-04-10 09:51:04 +03:00
|
|
|
caches.keys().then(keyList => {
|
|
|
|
return Promise.all(
|
|
|
|
keyList.map(key => {
|
|
|
|
if(key !== cacheName) {
|
|
|
|
return caches.delete(key);
|
|
|
|
}
|
|
|
|
})
|
|
|
|
);
|
2020-05-09 19:28:18 +03:00
|
|
|
})
|
|
|
|
);
|
|
|
|
});
|