I'm currently working on integrating a Service-Worker in my application. But I have problems when I want to test it on my local machine.
The caching in the install
-Event is failing. I searched for the error for two days but I don't have ideas anymore. When I deploy the site on e.g. netlify everything works fine.
That's what the network tab is giving me:
Developer console is printing:
Browser: Chromium Version 70.0.3538.77 (Official Build)
I activated #allow-insecure-localhost
in the chrome flags. Webpack is serving over https://localhost:8081
(with a self-signed certificate). If I right click the failed network requests and click Open in new tab
everything works fine.
The weird thing is that the failing files are changing every time.
Code in my index.jsx
(entry point for webpack):
...
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker
.register('/serviceWorker.js', { scope: "/" })
.then(e => {
console.log('Service Worker Registered');
console.log(e);
})
.catch(e => {
console.log("Service Worker fail");
console.log(e);
})
});
}
...
Code in my serviceWorker.js
let cacheName = 'test';
let cachedURLs = [
"/",
"/bundle.js",
"/manifest.webmanifest",
"/favicon.ico",
"/favicon-256.png"
];
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Caching app shell');
return cache.addAll(cachedURLs);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
Edit: As mentioned in the comments I added a catch
-block to the cache.addAll
:
return cache.addAll(cachedURLs).catch(err => console.log('error: ', err));
But unfortunately it isn't more verbose:
error: TypeError: Failed to fetch
For completeness this is what Chromium is reporting for a failed request (in this case it is the bundle.js
)