better cache handling

This commit is contained in:
or-else
2021-05-09 14:07:05 -07:00
parent e97e708c01
commit eeb14cf752
+12 -7
View File
@@ -56,7 +56,7 @@ fbMessaging.onBackgroundMessage((payload) => {
} }
// Notify webapp that a message was received. // Notify webapp that a message was received.
webAppChannel.postMessage(payload); webAppChannel.postMessage(payload.data);
const pushType = payload.data.what || 'msg'; const pushType = payload.data.what || 'msg';
const title = payload.data.title || self.i18nMessage(pushType == 'msg' ? 'new_message' : 'new_chat'); const title = payload.data.title || self.i18nMessage(pushType == 'msg' ? 'new_message' : 'new_chat');
@@ -121,29 +121,34 @@ self.addEventListener('notificationclick', event => {
// This is needed for 'Add to Home Screen'. // This is needed for 'Add to Home Screen'.
self.addEventListener('fetch', event => { self.addEventListener('fetch', event => {
if (event.request.method != 'GET') {
return;
}
event.respondWith((async () => { event.respondWith((async () => {
// Try to find response in cache. // Try to find the response in the cache.
const cachedResponse = await caches.match(event.request); const cache = await caches.open(PACKAGE_VERSION);
const cachedResponse = await cache.match(event.request);
if (cachedResponse) { if (cachedResponse) {
return cachedResponse; return cachedResponse;
} }
// Not found in cache. // Not found in cache.
const response = await fetch(event.request); const response = await fetch(event.request);
if (!response || response.status != 200 || response.type != 'basic' || event.request.method != 'GET') { if (!response || response.status != 200 || response.type != 'basic') {
return response; return response;
} }
if (event.request.url && (event.request.url.startsWith('http://') || event.request.url.startsWith('https://'))) { if (event.request.url && (event.request.url.startsWith('http://') || event.request.url.startsWith('https://'))) {
const cache = await caches.open(PACKAGE_VERSION);
await cache.put(event.request, response.clone()); await cache.put(event.request, response.clone());
} }
return response; return response;
})()); })());
}); });
// This code get the human language from the webapp. // This code gets the human language from the webapp.
// Locale is used for localization of strings.
self.addEventListener('message', event => { self.addEventListener('message', event => {
const data = JSON.parse(event.data); const data = JSON.parse(event.data);
// The locale is used for selecting strings in an appropriate language.
self.locale = data.locale || ''; self.locale = data.locale || '';
self.baseLocale = self.locale.toLowerCase().split(/[-_]/)[0]; self.baseLocale = self.locale.toLowerCase().split(/[-_]/)[0];
}); });