ServiceWorker (#1243)

- Create service worker to have PWA
 - Add install service worker
 - Add fecth service worker with a persistent cache navigator
 - Add favicon 512x512
This commit is contained in:
grégoire parant 2021-07-12 13:17:45 +02:00 committed by GitHub
parent ae9af56661
commit 022d1fec63
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 74 additions and 2 deletions

53
front/dist/resources/service-worker.js vendored Normal file
View File

@ -0,0 +1,53 @@
let CACHE_NAME = 'workavdenture-cache-v1';
let urlsToCache = [
'/'
];
self.addEventListener('install', function(event) {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request).then(
function(response) {
// Check if we received a valid response
if(!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// IMPORTANT: Clone the response. A response is a stream
// and because we want the browser to consume the response
// as well as the cache consuming the response, we need
// to clone it so we have two streams.
var responseToCache = response.clone();
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(event.request, responseToCache);
});
return response;
}
);
})
);
});
self.addEventListener('activate', function(event) {
//TODO activate service worker
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@ -119,7 +119,13 @@
"src": "/static/images/favicons/android-icon-192x192.png",
"sizes": "192x192",
"type": "image\/png",
"density": "4.0"
"density": "4.0",
"purpose": "any maskable"
},
{
"src": "/static/images/favicons/icon-512x512.png",
"sizes": "512x512",
"type": "image\/png"
}
],
"start_url": "/",
@ -127,6 +133,7 @@
"display_override": ["window-control-overlay", "minimal-ui"],
"display": "standalone",
"scope": "/",
"lang": "en",
"theme_color": "#000000",
"shortcuts": [
{
@ -134,7 +141,7 @@
"short_name": "WA",
"description": "WorkAdventure application",
"url": "/",
"icons": [{ "src": "/static/images/favicons/android-icon-192x192.png", "sizes": "192x192" }]
"icons": [{ "src": "/static/images/favicons/android-icon-192x192.png", "sizes": "192x192", "type": "image/png" }]
}
],
"description": "WorkAdventure application",

View File

@ -160,3 +160,15 @@ const app = new App({
})
export default app
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/resources/service-worker.js')
.then(serviceWorker => {
console.log("Service Worker registered: ", serviceWorker);
})
.catch(error => {
console.error("Error registering the Service Worker: ", error);
});
});
}