File Manager
Viewing File: sw.js
const CACHE_NAME = 'bankapp-v1.0.0';
const urlsToCache = [
'/',
'/dashboard',
'/offline.html',
'/css/app.css',
'/js/app.js',
'https://cdn.tailwindcss.com',
'https://unpkg.com/lucide@latest'
];
// Install event - cache resources
self.addEventListener('install', event => {
console.log('[ServiceWorker] Install');
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
console.log('[ServiceWorker] Caching app shell');
return cache.addAll(urlsToCache);
})
.catch(error => {
console.error('[ServiceWorker] Cache failed:', error);
})
);
self.skipWaiting();
});
// Fetch event - serve from cache, fallback to network
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
// Cache hit - return response
if (response) {
return response;
}
// Clone the request
const fetchRequest = event.request.clone();
return fetch(fetchRequest).then(response => {
// Check if valid response
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// Clone the response
const responseToCache = response.clone();
caches.open(CACHE_NAME)
.then(cache => {
cache.put(event.request, responseToCache);
});
return response;
});
})
.catch(error => {
console.error('[ServiceWorker] Fetch failed:', error);
// Return offline page for navigation requests
if (event.request.mode === 'navigate') {
return caches.match('/offline.html');
}
})
);
});
// Activate event - cleanup old caches
self.addEventListener('activate', event => {
console.log('[ServiceWorker] Activate');
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== CACHE_NAME) {
console.log('[ServiceWorker] Removing old cache:', cacheName);
return caches.delete(cacheName);
}
})
);
})
);
return self.clients.claim();
});
// Background sync
self.addEventListener('sync', event => {
if (event.tag === 'sync-transactions') {
event.waitUntil(syncTransactions());
}
});
async function syncTransactions() {
// Implement transaction sync logic
console.log('[ServiceWorker] Syncing transactions');
}
// Push notifications
self.addEventListener('push', event => {
const options = {
body: event.data ? event.data.text() : 'New notification',
icon: '/icon-192x192.png',
badge: '/badge-72x72.png',
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: 1
}
};
event.waitUntil(
self.registration.showNotification('Banking App', options)
);
});
// Notification click
self.addEventListener('notificationclick', event => {
event.notification.close();
event.waitUntil(
clients.openWindow('/')
);
});