-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
181 lines (163 loc) · 6.91 KB
/
service-worker.js
File metadata and controls
181 lines (163 loc) · 6.91 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
// service-worker.js
// service-worker.js
// Listener for the 'push' event, which is triggered when the server sends a notification.
self.addEventListener('push', event => {
console.log('[Service Worker] Push Received.');
// The data sent from your server. We'll assume it's a JSON string.
const pushData = event.data.json();
console.log('[Service Worker] Push data: ', pushData);
const title = pushData.title || 'AuraStream Notification';
const options = {
body: pushData.body || 'A new update is available!',
icon: pushData.icon || '/images/icon-192x192.png', // Path to a default notification icon
badge: pushData.badge || '/images/badge-72x72.png', // Path to a smaller badge icon
data: {
url: pushData.url || '/' // URL to open when the notification is clicked
}
};
// The waitUntil() method ensures the service worker doesn't terminate
// before the notification has been displayed.
event.waitUntil(self.registration.showNotification(title, options));
});
// Listener for the 'notificationclick' event.
self.addEventListener('notificationclick', event => {
console.log('[Service Worker] Notification click Received.');
// Close the notification pop-up.
event.notification.close();
const urlToOpen = event.notification.data.url || '/';
// The waitUntil() method here ensures that the browser doesn't terminate the
// service worker before the new window/tab has been displayed.
event.waitUntil(
clients.matchAll({
type: "window"
}).then(clientList => {
// If a window for the app is already open, focus it.
for (const client of clientList) {
if (client.url === urlToOpen && 'focus' in client) {
return client.focus();
}
}
// Otherwise, open a new window.
if (clients.openWindow) {
return clients.openWindow(urlToOpen);
}
})
);
});
/*
// Versioning the service worker cache (important for updates)
const CACHE_NAME = 'auraStream-v1';
// List files to pre-cache (optional, but good for offline experience)
const urlsToCache = [
'/', // Root page
'sm4movies.html',
'css/style.css', // If you extract your style block
'js/firebase.js',
'js/analytics.js',
// Add other essential static assets: fonts, main images etc.
];
// Install event: cache assets
self.addEventListener('install', (event) => {
console.log('[Service Worker] Installing...');
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => {
console.log('[Service Worker] Caching all app shell');
return cache.addAll(urlsToCache);
})
.catch(error => {
console.error('[Service Worker] Cache installation failed:', error);
})
);
});
// Activate event: clean up old caches
self.addEventListener('activate', (event) => {
console.log('[Service Worker] Activating...');
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== CACHE_NAME) {
console.log('[Service Worker] Deleting old cache:', cacheName);
return caches.delete(cacheName);
}
})
);
})
);
// Ensure the service worker takes control of the page immediately
return self.clients.claim();
});
// Fetch event: serve from cache, then network
self.addEventListener('fetch', (event) => {
// Only handle HTTP/HTTPS requests
if (event.request.url.startsWith('http')) {
event.respondWith(
caches.match(event.request)
.then((response) => {
// Cache hit - return response
if (response) {
return response;
}
// Not in cache - fetch from network
return fetch(event.request)
.then((fetchResponse) => {
// If response is valid, clone it and cache it
if (fetchResponse.ok) {
const responseToCache = fetchResponse.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, responseToCache);
});
}
return fetchResponse;
});
})
.catch((error) => {
console.error('[Service Worker] Fetch failed:', error);
// You can return a fallback page here for offline
// return caches.match('/offline.html');
})
);
}
});
// Push notification event: handle incoming push messages
self.addEventListener('push', (event) => {
console.log('[Service Worker] Push Received.');
// Parse the push message payload
const data = event.data ? event.data.json() : {};
const title = data.title || 'AuraStream Notification';
const options = {
body: data.body || 'A new update or reminder from AuraStream.',
icon: data.icon || '/path/to/your/app-icon-192x192.png', // Replace with your app icon
badge: data.badge || '/path/to/your/app-badge-72x72.png', // Optional: smaller icon for mobile status bar
image: data.image || '', // Optional: large image for richer notifications
data: {
url: data.url || '/', // URL to open when notification is clicked
},
actions: data.actions || [], // Optional: notification action buttons
vibrate: [200, 100, 200], // Optional: vibration pattern
tag: data.tag, // Optional: tag to group/replace notifications
renotify: data.renotify || false, // Optional: renotify if tag matches existing notification
};
event.waitUntil(self.registration.showNotification(title, options));
});
// Notification click event: handle user interaction with the notification
self.addEventListener('notificationclick', (event) => {
console.log('[Service Worker] Notification click received.');
event.notification.close(); // Close the notification
const targetUrl = event.notification.data.url || '/'; // Get URL from notification data
event.waitUntil(
clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
// Check if there's an existing client (tab/window) for the app
for (const client of clientList) {
if (client.url.includes(self.location.origin) && 'focus' in client) {
// If an existing client matches, focus it and navigate to URL
return client.focus().then(focusedClient => focusedClient.navigate(targetUrl));
}
}
// If no existing client, open a new window
return clients.openWindow(targetUrl);
})
);
});
*/