-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
340 lines (300 loc) Β· 9.41 KB
/
service-worker.js
File metadata and controls
340 lines (300 loc) Β· 9.41 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Minimal Service Worker for PWA Installation
const CACHE_NAME = 'notification-viewer-v2.1.0';
const STATIC_CACHE = 'static-cache-v2.1.0';
// Essential files to cache for offline functionality
// Essential files to cache for offline functionality
const STATIC_ASSETS = [
'/',
'/index.html',
'/manifest.json',
'/browserconfig.xml',
// Critical icons for offline functionality
'/icons/android/android-launchericon-192-192.png',
'/icons/android/android-launchericon-512-512.png',
'/icons/ios/180.png',
'/icons/ios/32.png',
'/icons/ios/16.png',
// External dependencies that are critical
'https://cdn.tailwindcss.com',
'https://fonts.googleapis.com/icon?family=Material+Icons',
'https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap',
'https://cdnjs.cloudflare.com/ajax/libs/mqtt/5.7.0/mqtt.min.js'
];
// Install event - cache essential resources
self.addEventListener('install', (event) => {
console.log('π§ Service Worker installing...');
// Skip waiting to activate immediately
self.skipWaiting();
event.waitUntil(
caches.open(STATIC_CACHE)
.then((cache) => {
console.log('π¦ Caching static assets');
// Cache essential files, but don't fail if some external resources fail
return Promise.allSettled(
STATIC_ASSETS.map(url =>
cache.add(url).catch(err => {
console.warn('β οΈ Failed to cache:', url, err);
return null;
})
)
);
})
.then(() => {
console.log('β
Service Worker installed successfully');
})
.catch((error) => {
console.error('β Service Worker installation failed:', error);
})
);
});
// Activate event - take control and clean up old caches
self.addEventListener('activate', (event) => {
console.log('π Service Worker activating...');
event.waitUntil(
Promise.all([
// Clean up old caches
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== CACHE_NAME && cacheName !== STATIC_CACHE) {
console.log('ποΈ Deleting old cache:', cacheName);
return caches.delete(cacheName);
}
})
);
}),
// Take control of all clients immediately
self.clients.claim()
]).then(() => {
console.log('β
Service Worker activated and claimed clients');
// Notify all clients about activation
return self.clients.matchAll();
}).then(clients => {
clients.forEach(client => {
client.postMessage({
type: 'SW_ACTIVATED',
message: 'Service Worker activated successfully'
});
});
}).catch((error) => {
console.error('β Service Worker activation failed:', error);
})
);
});
// Fetch event - serve cached content when offline
self.addEventListener('fetch', (event) => {
const { request } = event;
const url = new URL(request.url);
// Only handle GET requests
if (request.method !== 'GET') {
return;
}
// Skip non-http requests
if (!url.protocol.startsWith('http')) {
return;
}
// Skip MQTT WebSocket connections
if (url.protocol.startsWith('ws')) {
return;
}
event.respondWith(
handleFetch(request)
);
});
async function handleFetch(request) {
const url = new URL(request.url);
try {
// For the main document, try network first, then cache
if (request.mode === 'navigate') {
try {
const response = await fetch(request);
// Cache successful responses
if (response.status === 200) {
const cache = await caches.open(STATIC_CACHE);
cache.put(request, response.clone());
}
return response;
} catch (error) {
// Network failed, try cache
const cached = await caches.match('/index.html');
if (cached) {
return cached;
}
// Return a basic offline page
return new Response(`
<!DOCTYPE html>
<html>
<head>
<title>Offline - Morph Messaging</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body { font-family: system-ui; text-align: center; padding: 2rem; }
.offline { color: #666; }
</style>
</head>
<body>
<h1>π‘ Offline</h1>
<p class="offline">You're currently offline. Please check your connection and try again.</p>
<button onclick="location.reload()">π Retry</button>
</body>
</html>
`, {
headers: { 'Content-Type': 'text/html' }
});
}
}
// For static assets, try cache first, then network
const cached = await caches.match(request);
if (cached) {
// Serve from cache, but update in background
fetch(request).then(response => {
if (response.status === 200) {
caches.open(STATIC_CACHE).then(cache => {
cache.put(request, response);
});
}
}).catch(() => {
// Network failed, but we have cache
});
return cached;
}
// Not in cache, try network
const response = await fetch(request);
// Cache successful responses for static assets
if (response.status === 200 && (
url.hostname === location.hostname ||
url.hostname === 'cdn.tailwindcss.com' ||
url.hostname === 'fonts.googleapis.com' ||
url.hostname === 'cdnjs.cloudflare.com'
)) {
const cache = await caches.open(STATIC_CACHE);
cache.put(request, response.clone());
}
return response;
} catch (error) {
console.error('Fetch failed:', error);
// Return cached version if available
const cached = await caches.match(request);
if (cached) {
return cached;
}
// Return a simple error response
return new Response('Network error occurred', {
status: 503,
statusText: 'Service Unavailable'
});
}
}
// Handle push notifications
self.addEventListener('push', (event) => {
console.log('π¨ Push notification received');
let notificationData = {
title: 'Morph Messaging',
body: 'New notification received',
icon: '/icons/icon-192.png',
badge: '/icons/icon-96.png',
tag: 'default',
data: {}
};
if (event.data) {
try {
const data = event.data.json();
notificationData = {
...notificationData,
title: data.title || notificationData.title,
body: data.body || data.message || notificationData.body,
icon: data.icon || notificationData.icon,
tag: data.tag || `notification-${Date.now()}`,
data: data,
actions: [
{
action: 'open',
title: 'ποΈ View',
icon: '/icons/icon-96.png'
},
{
action: 'dismiss',
title: 'β Dismiss',
icon: '/icons/icon-96.png'
}
],
requireInteraction: data.priority === 'high',
silent: data.priority === 'low'
};
} catch (error) {
console.error('Error parsing push data:', error);
}
}
event.waitUntil(
self.registration.showNotification(notificationData.title, notificationData)
);
});
// Handle notification clicks
self.addEventListener('notificationclick', (event) => {
console.log('π Notification clicked:', event.action);
event.notification.close();
if (event.action === 'dismiss') {
return;
}
// Default action or 'open'
let urlToOpen = '/';
if (event.notification.data) {
const data = event.notification.data;
if (data.notificationId) {
urlToOpen = `/?notification=${data.notificationId}`;
} else if (data.jobOrderId) {
urlToOpen = `/?joborder=${data.jobOrderId}`;
}
}
event.waitUntil(
self.clients.matchAll({ type: 'window', includeUncontrolled: true })
.then(clients => {
// Check if app is already open
for (const client of clients) {
if (client.url.includes(urlToOpen.split('?')[0])) {
return client.focus().then(() => {
client.postMessage({
type: 'NOTIFICATION_CLICKED',
data: event.notification.data,
url: urlToOpen
});
});
}
}
// Open new window
return self.clients.openWindow(urlToOpen);
})
);
});
// Handle messages from main thread
self.addEventListener('message', (event) => {
// Ignore extension messages and other non-app messages
if (!event.data || typeof event.data !== 'object' || !event.data.type) {
return;
}
const { type, data } = event.data;
switch (type) {
case 'SKIP_WAITING':
self.skipWaiting();
break;
case 'CLAIM_CLIENTS':
self.clients.claim();
break;
case 'GET_VERSION':
event.ports[0]?.postMessage({
version: CACHE_NAME,
timestamp: new Date().toISOString()
});
break;
default:
console.log('Unknown message type:', type);
}
});
// Global error handling
self.addEventListener('error', (event) => {
console.error('π₯ Service Worker error:', event.error);
});
self.addEventListener('unhandledrejection', (event) => {
console.error('π₯ Unhandled promise rejection in SW:', event.reason);
});
console.log('π Service Worker script loaded - v' + CACHE_NAME);