-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
84 lines (77 loc) · 2.44 KB
/
sw.js
File metadata and controls
84 lines (77 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// --- CONFIGURATION ---
const APP_VERSION = 'v1.5.7';
const CACHE_NAME = `pro-file-tools-${APP_VERSION}`;
// --- INSTALL EVENT (Fault-Tolerant) ---
self.addEventListener('install', (event) => {
self.skipWaiting();
event.waitUntil(
caches.open(CACHE_NAME).then(async (cache) => {
// 1. Critical File (Must exist for the app to work)
// We only strictly require the homepage.
try {
await cache.add('./');
await cache.add('./index.html');
} catch (err) {
console.error('[SW] Critical failure: Could not cache index.html', err);
}
// 2. Optional Files
// If these are missing, the app will still install successfully.
const optionalAssets = [
'./manifest.json',
'./icons.js',
'./metadata.js',
'./tools.js',
'./mrbtoolslogo.jpg'
];
// Try to cache each one individually
for (const asset of optionalAssets) {
try {
const response = await fetch(asset);
if (response.ok) {
await cache.put(asset, response);
} else {
console.warn(`[SW] File not found (404): ${asset}`);
}
} catch (err) {
console.warn(`[SW] Failed to cache optional file: ${asset}`);
}
}
})
);
});
// --- ACTIVATE EVENT (Cleanup) ---
self.addEventListener('activate', (event) => {
event.waitUntil(clients.claim());
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cache) => {
// Delete old versions of this specific app
if (cache.startsWith('pro-file-tools-') && cache !== CACHE_NAME) {
console.log(`[SW] Deleting old cache: ${cache}`);
return caches.delete(cache);
}
})
);
})
);
});
// --- FETCH EVENT ---
self.addEventListener('fetch', (event) => {
// Only handle http/https requests
if (!event.request.url.startsWith('http')) return;
event.respondWith(
fetch(event.request)
.then((response) => {
// If network works, update cache
if (!response || response.status !== 200 || response.type !== 'basic') return response;
const responseToCache = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, responseToCache));
return response;
})
.catch(() => {
// If offline, try cache
return caches.match(event.request);
})
);
});