With a PWA, we can handle when the device connection is down with offline mode. But how do we detect a fixed network connection and automatically reload/re-activate the application?
Our app is caching its resources on install and serving them with fetch from the cache, so it works even if the user is offline.
Using a service worker, a Progressive Web App (PWA) can do work in the background, even when the user isn't using the app. Service workers used to be reserved for native apps, but they are now also available to PWAs, providing a better offline experience.
Publishing the app to digital distribution systems like Apple App Store or Google Play is optional. As of 2021, PWA features are supported to varying degrees by Google Chrome, Apple Safari, Firefox for Android, and Microsoft Edge but not by Firefox for desktop.
You could monitor the offline
and online
events, which are widely supported. Further, you could test connectivity by attempting to fetch HEAD
from the target server URL:
// Test this by running the code snippet below and then // use the "Offline" checkbox in DevTools Network panel window.addEventListener('online', handleConnection); window.addEventListener('offline', handleConnection); function handleConnection() { if (navigator.onLine) { isReachable(getServerUrl()).then(function(online) { if (online) { // handle online status console.log('online'); } else { console.log('no connectivity'); } }); } else { // handle offline status console.log('offline'); } } function isReachable(url) { /** * Note: fetch() still "succeeds" for 404s on subdirectories, * which is ok when only testing for domain reachability. * * Example: * https://google.com/noexist does not throw * https://noexist.com/noexist does throw */ return fetch(url, { method: 'HEAD', mode: 'no-cors' }) .then(function(resp) { return resp && (resp.ok || resp.type === 'opaque'); }) .catch(function(err) { console.warn('[conn test failure]:', err); }); } function getServerUrl() { return document.getElementById('serverUrl').value || window.location.origin; }
<fieldset> <label> <span>Server URL for connectivity test:</span> <input id="serverUrl" style="width: 100%"> </label> </fieldset> <script>document.getElementById('serverUrl').value = window.location.origin;</script> <p> <i>Use Network Panel in DevTools to toggle Offline status</i> </p>
One technique of handling this:
Offline event
Online event
Be careful with the online
event, that only tells the device if connected. It can be connected to a WiFi hotspot without actual Internet connectivity (because of credentials for example).
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