Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make ServiceWorker survive cache reset/Shift+F5?

I want to create a website that can work even when it's server is offline — I found that that's what ServiceWorkers are for.

When I reload the page with service worker and no connectivity, it works just fine. However, shift+reload (e.g. bypassing cache) disarms service worker and I get "could not connect to server" error.

My question is — can I somehow prevent shift+reload (shift+f5, ctrl+f5 etc) from ruining service worker, or, at least, make it recover afterwards without restoring connectivity?

like image 487
toriningen Avatar asked Jun 01 '16 04:06

toriningen


1 Answers

I was able to keep using the service worker even after Ctrl+F5 via the following approach:

In the window script:

navigator.serviceWorker.register(<...>).then (registration => {
    if (navigator.serviceWorker.controller === null) {
        // we get here after a ctrl+f5 OR if there was no previous service worker.
        navigator.serviceWorker.ready.then(() => {
            registration.active.postMessage("claimMe");
        });
    }
    <...>
});

In the service script:

self.onmessage = (event) => {
    if (event.data === "claimMe") {
        self.clients.claim();
    }
};

In short, we ask the service worker to claim all clients again, which works even for clients that used Ctrl+F5.

If you want to respect the Ctrl+F5 in the service worker code, you could either:

  1. Clear the cache before claiming. Note that this will also affect any other existing clients, which may be unwanted.
  2. Do something more complicated like sending the id of the client that requested a Ctrl+F5 and treat fetch requests specially for such clients.
like image 143
secondperson Avatar answered Sep 30 '22 04:09

secondperson