36037-vm/service-worker.js
Flatlogic Bot 4d1d667390 version 2
2025-11-22 17:22:34 +00:00

81 lines
2.8 KiB
JavaScript

const CACHE_NAME = 'opulent-pos-cache-v2';
const urlsToCache = [
'/',
'/index.php',
'/dashboard.php',
'/dashboard.php?view=cashier_checkout',
'/manifest.json',
'/assets/css/custom.css',
'/assets/js/main.js',
'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css',
'https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css'
];
self.addEventListener('install', event => {
self.skipWaiting(); // Activate worker immediately
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
console.log('Opened cache and caching assets');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('activate', event => {
const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
console.log('Deleting old cache:', cacheName);
return caches.delete(cacheName);
}
})
);
})
.then(() => self.clients.claim()) // Take control of all clients
);
});
self.addEventListener('fetch', event => {
// We only want to cache GET requests
if (event.request.method !== 'GET') {
return;
}
event.respondWith(
caches.open(CACHE_NAME).then(async (cache) => {
// Try to get the response from the cache
const cachedResponse = await cache.match(event.request);
// Return the cached response if found
if (cachedResponse) {
// Re-fetch in the background to update the cache for next time
fetch(event.request).then(response => {
if (response.ok) {
cache.put(event.request, response.clone());
}
});
return cachedResponse;
}
// If not in cache, fetch from the network
try {
const networkResponse = await fetch(event.request);
// If the fetch is successful, clone it and store it in the cache
if (networkResponse.ok) {
cache.put(event.request, networkResponse.clone());
}
return networkResponse;
} catch (error) {
// If the fetch fails (e.g., offline), return a fallback or an error
console.log('Fetch failed; returning offline page instead.', error);
// You could return a generic offline page here if you had one
// For now, just let the browser handle the error
}
})
);
});