Service worker only fetches url from cache when adding “index.html”

148
August 07, 2019, at 7:40 PM

I use a serviceworker to serve content offline. The following code works well except when I refresh the page in offline mode right after opening and installing the serviceworker in online-mode. All these scenarios work: 1. Loading the page online, refreshing the page onlinge -> refreshing the page offline - works. 2. Loading "/offline-test/" online -> loading "/offline-test/index.html" offline - works 3. Loading "/offline-test/index.html/ online -> loading "/offline-test/" offline - works Only this scenario isn't working: Loading the page online -> refresh the page in offline-mode.

Why?

I'm using Chrome Dev tools to simulate Offline-Mode. Same problem in Firefox (turning WiFi off after loading the page).

index.html

<HTML>
...
<BODY>
...
</BODY>
<SCRIPT>
        if('serviceWorker' in navigator) {
            navigator.serviceWorker.register('../sw.js')
                .then(function() {
                    console.log("Service Worker Registered");
                });
        }
    </SCRIPT>
</HTML>

sw.js

self.addEventListener('install', function(e) {
//  self.skipWaiting();
    if(navigator.onLine) {
        console.log('Navigator is online');
        e.waitUntil(caches.keys()
            .then(function(keyList) {
                console.log('Try to delete cache.');
                return Promise.all(keyList.map(function(key) {
                    return caches.delete(key)
                        .then(function(response) {
                            console.log('Cache-Key '+key+' will be deleted');
                            return response;
                        }, function(reject) {
                            consoloe.log('Failure deleting '+key);
                            return reject;
                        });
                }))
            })
        );
    }
    e.waitUntil(
        caches.open('offline-test-v3').then(function(cache) {
            console.log('index.html and all the others will be added to cache');
            return cache.addAll([
                'offline-test/',
                'offline-test/index.html',
                'offline-test/style.css',
                'offline-test/logo-192.png',
                'offline-test/fonts/ROCK.TTF',
                'manifest.json',
                'offline-test/favicon.ico'
            ])
                .then(function(response) {
                    console.log('Everything succesfully added to cache');
                });
        })
    );
});
self.addEventListener('activate', function(ev) {
//  ev.waitUntil(self.clients.claim());
//  clients.claim();
//  ev.waitUntil(clients.claim());
    console.log('I\'m activated');
});
self.addEventListener('update', function(eve) {
    console.log('I\'m updated');
});
self.addEventListener('fetch', function(event) {
    console.log('Will fetch '+event.request.url);
    //Networ first
    event.respondWith(
        fetch(event.request).catch(function() {
            console.log('Try to fetch '+event.request.url+' from cache');
            return caches.match(event.request);
        })
    );

console after loading index.html online

Service Worker Registered
sw.js:9 Navigator is online
sw.js:12 Try to delete cache.
sw.js:29 index.html and all the others will be added to cache
sw.js:40 Everything succesfully added to cache
sw.js:58 I'm activated

console after refreshing in offline-mode

Will fetch index.html
sw.js:70 Try to fetch [url]/index.html from cache
The FetchEvent for [url]/index.html" resulted in a network error response: an object that was not a Response was passed to respondWith().
Answer 1

Solved this issue by adding the new cache as a resolve to the preceding cache-deleting-routine. Probably the two threads conflicted.

New sw.js

self.addEventListener('install', function(e) {  
    if(navigator.onLine) {
        console.log('Navigator is online');
        e.waitUntil(caches.keys()
        .then(function(keyList) {
            console.log('Try to delete cache.');
            return Promise.all(keyList.map(function(key) {
                return caches.delete(key)
                    .then(function(response) {
                        console.log('Cache-Key '+key+' will be deleted');
                        return response;
                    }, function(reject) {
                        consoloe.log('Failure deleting '+key);
                        return reject;
                    });
            }))
        })
        .then(function() {
            caches.open('offline-test-v3').then(function(cache) {
                console.log('index.html and all the others will be added to cache');
                return cache.addAll([
                    'offline-test/',
                    'offline-test/index.html',
                    'offline-test/style.css',
                    'offline-test/logo-192.png',
                    'offline-test/fonts/ROCK.TTF',
                    'manifest.json',
                    'offline-test/favicon.ico'
                ])
                .then(function(response) {
                    console.log('Everything succesfully added to cache');
                });
            })
        }));
    }
});
self.addEventListener('activate', function(ev) {
    console.log('I\'m activated');
});
self.addEventListener('update', function(eve) {
    console.log('I\'m updated');
});
self.addEventListener('fetch', function(event) {
    console.log('Will fetch '+event.request.url);
    //Network first
    event.respondWith(
        fetch(event.request)
            .then(function(resolve) {
                console.log('Fetched '+event.request.url+' via the browser way.');
                return resolve;
            }, function(reject) {
                console.log('Try to fetch '+event.request.url+' via the serviceworker way');
                return caches.match(event.request);
            })
        );
/*  if(!navigator.onLine) {
        console.log('Try to fetch '+event.request.url+' from cache.');
        event.respondWith(caches.match(event.request)
            .then(function(response) {
                return response || fetch(event.request);
            })
        );
    }*/
});
Rent Charter Buses Company
READ ALSO
Django/Webpack - How to serve generated webpack bundles with webpack dev server

Django/Webpack - How to serve generated webpack bundles with webpack dev server

Django's 'static' tag generates urls using STATIC_URL, which results in something like '/static/myapp/js/bundlejs' Mean while, webpack-dev-server is serving bundles from the url 'localhost:3000'

192
React Arrow Function Component - setState is not defined

React Arrow Function Component - setState is not defined

I am trying to setState in an arrow function component but getting an error "setState is not defined"

380
Certain documents uploaded through Typescript are corrupt (WebKitFormBoundary

Certain documents uploaded through Typescript are corrupt (WebKitFormBoundary

I have a process through Typescript that uploads filesCertain file types are uploading OK (PDF) but other file types (DOCX for example) are noted as corrupted when the user tries to open them from the location they were uploaded to

141
How to set cookies in Chrome Extension with js

How to set cookies in Chrome Extension with js

I'm trying to set Cookies with a Google Chrome Extension coded in Javascript but somehow I don't get my cookies set

224