Files
Iris/mopidy_iris/static/service-worker.js

67 lines
1.9 KiB
JavaScript
Raw Normal View History

const blacklist = [
'jamesbarnsley.co.nz',
'following/contains',
'followers/contains',
2019-09-26 10:22:43 +12:00
'me/tracks',
'me/albums',
'me/following',
2021-03-23 21:21:00 +13:00
'refresh_spotify_token',
];
function inBlacklist(url) {
for (const item of blacklist) {
if (url.indexOf(item) >= 0) {
return true;
}
}
return false;
}
2021-03-23 21:21:00 +13:00
self.addEventListener('activate', (event) => {
event.waitUntil(
2021-03-23 21:21:00 +13:00
caches.keys().then((cacheNames) => Promise.all(cacheNames.map((cacheName) => caches.delete(cacheName)))),
);
});
self.addEventListener('fetch', (event) => {
const { request } = event;
event.respondWith(
// Opens Cache objects that start with 'font'.
2021-03-23 21:21:00 +13:00
caches.open('iris').then((cache) => cache.match(request)
.then((response) => {
if (response) {
return response;
}
2021-03-23 21:21:00 +13:00
// Not cached, so we make the request, return that and also save response in cache
return fetch(request)
.then((liveResponse) => {
const isBlacklisted = inBlacklist(request.url);
2021-03-23 21:21:00 +13:00
// Only cache successful GET requests
if (
!isBlacklisted
&& request.method === 'GET'
&& liveResponse.status >= 200
&& liveResponse.status < 400
2021-03-23 21:21:00 +13:00
) {
// Fixes Edge browser "'chrome-extension' is unsupported" issue
// See https://stackoverflow.com/questions/49157622/service-worker-typeerror-when-opening-chrome-extension
if (!/^https?:$/i.test(new URL(request.url).protocol)) return;
2021-03-23 21:21:00 +13:00
cache.put(request, liveResponse.clone());
} else {
console.info(`Not caching ${isBlacklisted ? '(blacklisted) ' : ''}${request.method} ${request.url}`);
}
2021-03-23 21:21:00 +13:00
return liveResponse;
});
// Exceptions from match() or fetch()
2021-03-23 21:21:00 +13:00
}).catch((error) => {
throw error;
})),
);
});