- I am trying to build a PWA with an offline first policy.
- The server for the source files is a NodeJS server.
- I am currently testing this on a localhost node server (not sure it has an impact ?).
- Service worker + caching seems fine, but in offline mode I only get the Chrome Offline Page.
Let's get into details :
The page which is served (through the http://localhost:8080/place/test url) has some client side JS, in which I register a Service Worker :
client.js
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register(rootPath+'/js/service-worker.js')
.then(function() { console.log('Service Worker Registered'); });
}
service-worker.js (based on the Google PWA tutorial)
var cacheName = 'myCacheVersion';
var filesToCache = [
'../',
'../place/test',
'../js/client.js',
'../js/service-worker.js',
"../css/style.css"
];
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(filesToCache);
})
);
});
self.addEventListener('activate', function(e) {
console.log('[ServiceWorker] Activate');
e.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (key !== cacheName) {
console.log('[ServiceWorker] Removing old cache', key);
return caches.delete(key);
}
}));
})
);
return self.clients.claim();
});
self.addEventListener('fetch', function(e) {
console.log('[ServiceWorker] Fetch', e.request.url);
e.respondWith(
caches.match(e.request).then(function(response) {
return response || fetch(e.request);
})
);
});
In the Dev Tools Console, everything seems fine :
- The SW is registered
- The cache contains the elements I wanted to cache
But when I check the Offline mode checkbox and refresh my page url : http://localhost:8080/place/test , I only get the Google Chrome Offline Web Page.
=> What am I missing there ? (does it have to do with nodeJs ? with the localhost environment ? with my implementation ?)
I've been struggling with this one for a little while now...
I have checked in the "Application" tab and my service worker shows up as activated and is running.
Note : If found a similar question here, but no satisfying answer over there : Service worker not run in offline mode using nodejs server