'use strict'; // Register the service worker if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/service-worker.js') .then(registration => { console.log('ServiceWorker registration successful with scope: ', registration.scope); }) .catch(err => { console.log('ServiceWorker registration failed: ', err); }); }); // Add message listener for SW communication navigator.serviceWorker.addEventListener('message', event => { if (event.data && event.data.type === 'SW_VERSION_MISMATCH') { console.log('Client received SW_VERSION_MISMATCH message:', event.data.payload); const SW_UNREGISTER_THROTTLE_MS = 15 * 60 * 1000; // 15 minutes const LAST_ATTEMPT_KEY = 'swLastUnregisterAttempt'; const lastAttemptTimestamp = localStorage.getItem(LAST_ATTEMPT_KEY); const now = Date.now(); if (lastAttemptTimestamp && (now - parseInt(lastAttemptTimestamp, 10) < SW_UNREGISTER_THROTTLE_MS)) { console.warn(`SW version mismatch detected, but throttling unregister attempt. Last attempt was less than ${SW_UNREGISTER_THROTTLE_MS / 1000}s ago.`); return; // Throttled } console.log('SW version mismatch detected. Attempting to unregister service worker and reload.'); localStorage.setItem(LAST_ATTEMPT_KEY, now.toString()); navigator.serviceWorker.getRegistration().then(registration => { if (registration) { registration.unregister().then(unregistered => { if (unregistered) { console.log('Service worker unregistered successfully.'); // Force reload from network, bypassing cache window.location.reload(true); } else { console.error('Failed to unregister service worker.'); } }).catch(err => { console.error('Error unregistering service worker:', err); }); } else { console.warn('No active service worker registration found to unregister.'); // Still reload, might fix the issue if registration was stuck window.location.reload(true); } }); } }); }