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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With