Recommendations for detecting an offline condition by a service worker

I have a worker who should cache the offline.html page, which is displayed if the client does not have a network connection. However, sometimes he believes that the navigator is turned off, even if it is not. That is, navigator.onLine === false . This means that the user can get offline.html instead of the actual content even on the Internet, which, obviously, I would like to avoid.

This is how I register a service worker in my main.js :

 // Install service worker for offline use and caching if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/service-worker.js', {scope: '/'}); } 

My current service-worker.js :

 const OFFLINE_URL = '/mysite/offline'; const CACHE_NAME = 'mysite-static-v1'; self.addEventListener('install', (event) => { event.waitUntil( // Cache the offline page when installing the service worker fetch(OFFLINE_URL, { credentials: 'include' }).then(response => caches.open(CACHE_NAME).then(cache => cache.put(OFFLINE_URL, response)), ), ); }); self.addEventListener('fetch', (event) => { const requestURL = new URL(event.request.url); if (requestURL.origin === location.origin) { // Load static assets from cache if network is down if (/\.(css|js|woff|woff2|ttf|eot|svg)$/.test(requestURL.pathname)) { event.respondWith( caches.open(CACHE_NAME).then(cache => caches.match(event.request).then((result) => { if (navigator.onLine === false) { // We are offline so return the cached version immediately, null or not. return result; } // We are online so let run the request to make sure our content // is up-to-date. return fetch(event.request).then((response) => { // Save the result to cache for later use. cache.put(event.request, response.clone()); return response; }); }), ), ); return; } } if (event.request.mode === 'navigate' && navigator.onLine === false) { // Uh-oh, we navigated to a page while offline. Let show our default page. event.respondWith(caches.match(OFFLINE_URL)); return; } // Passthrough for everything else event.respondWith(fetch(event.request)); }); 

What am I doing wrong?

+5
source share
1 answer

navigator.onLine and related events can be useful when you want to update your user interface to indicate that you are offline and, for example, show only content that exists in the cache.

But I would not write the logic of the working operator, which relies on checking navigator.onLine . Instead, try fetch() unconditionally, and if that fails, provide a backup response. This ensures that your web application will behave as expected, regardless of whether fetch() crashes due to offline failure due to lie-fi or due to problems with the web server.

 // Other fetch handler code... if (event.request.mode === 'navigate') { return event.respondWith( fetch(event.request).catch(() => caches.match(OFFLINE_URL)) ); } // Other fetch handler code... 
+3
source

Source: https://habr.com/ru/post/1271497/


All Articles