diff --git a/Frontend/public/offline.html b/Frontend/public/offline.html new file mode 100644 index 0000000..7a09729 --- /dev/null +++ b/Frontend/public/offline.html @@ -0,0 +1,196 @@ + + + + + + You're Offline - Rehabify + + + +
+
+ + + +
+

You're Currently Offline

+

Don't worry! You can still access previously loaded content. We'll automatically reconnect when your internet connection is restored.

+
+ + +
+
+ + Checking connection status... +
+
+ + + \ No newline at end of file diff --git a/Frontend/public/service-worker.js b/Frontend/public/service-worker.js new file mode 100644 index 0000000..69e05d7 --- /dev/null +++ b/Frontend/public/service-worker.js @@ -0,0 +1,51 @@ +const CACHE_NAME = 'offline-v1'; +const OFFLINE_URL = '/offline.html'; + +self.addEventListener('install', (event) => { + event.waitUntil( + (async () => { + const cache = await caches.open(CACHE_NAME); + // Cache the offline page + await cache.add(new Request(OFFLINE_URL, { cache: 'reload' })); + })() + ); + // Force the waiting service worker to become the active service worker + self.skipWaiting(); +}); + +self.addEventListener('activate', (event) => { + event.waitUntil( + (async () => { + // Enable navigation preload if available + if ('navigationPreload' in self.registration) { + await self.registration.navigationPreload.enable(); + } + })() + ); + // Tell the active service worker to take control of the page immediately + self.clients.claim(); +}); + +self.addEventListener('fetch', (event) => { + if (event.request.mode === 'navigate') { + event.respondWith( + (async () => { + try { + // First, try to use the navigation preload response if available + const preloadResponse = await event.preloadResponse; + if (preloadResponse) { + return preloadResponse; + } + + // Try to fetch the request from the network + return await fetch(event.request); + } catch (error) { + // If fetch fails (offline), get the offline page from cache + const cache = await caches.open(CACHE_NAME); + const cachedResponse = await cache.match(OFFLINE_URL); + return cachedResponse; + } + })() + ); + } +}); \ No newline at end of file diff --git a/Frontend/src/main.tsx b/Frontend/src/main.tsx index 4cf90e1..5c9aac2 100644 --- a/Frontend/src/main.tsx +++ b/Frontend/src/main.tsx @@ -4,6 +4,18 @@ import ReactDOM from 'react-dom/client' import App from './App' import './index.css' +if ('serviceWorker' in navigator) { + window.addEventListener('load', () => { + navigator.serviceWorker.register('/service-worker.js') + .then(registration => { + console.log('ServiceWorker registration successful'); + }) + .catch(err => { + console.log('ServiceWorker registration failed: ', err); + }); + }); + } + ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(