Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
308 lines (280 loc) · 10.8 KB
/
Copy pathindex.html
File metadata and controls
308 lines (280 loc) · 10.8 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Push Server Demo</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 50px auto;
padding: 20px;
background: #f5f5f5;
}
.container {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 {
color: #333;
margin-bottom: 30px;
}
.section {
margin-bottom: 30px;
padding: 20px;
background: #f9f9f9;
border-radius: 5px;
}
button {
padding: 12px 24px;
font-size: 16px;
border: none;
border-radius: 5px;
cursor: pointer;
margin: 5px;
transition: background 0.3s;
}
.btn-primary {
background: #007bff;
color: white;
}
.btn-primary:hover {
background: #0056b3;
}
.btn-success {
background: #28a745;
color: white;
}
.btn-success:hover {
background: #1e7e34;
}
.btn-danger {
background: #dc3545;
color: white;
}
.btn-danger:hover {
background: #bd2130;
}
.status {
padding: 15px;
border-radius: 5px;
margin-top: 15px;
}
.status.success {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.status.error {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.status.info {
background: #d1ecf1;
color: #0c5460;
border: 1px solid #bee5eb;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
.stats {
font-size: 18px;
font-weight: bold;
color: #007bff;
}
pre {
background: #f4f4f4;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
font-size: 12px;
}
</style>
</head>
<body>
<div class="container">
<h1>🔔 Web Push Server Demo</h1>
<div class="section">
<h2>1. Subscribe to Notifications</h2>
<button id="subscribeBtn" class="btn-primary">Subscribe</button>
<button id="unsubscribeBtn" class="btn-danger">Unsubscribe</button>
<div id="subscribeStatus"></div>
</div>
<div class="section">
<h2>2. Send Test Notification</h2>
<input type="text" id="notifTitle" placeholder="Notification Title" value="Hello!">
<input type="text" id="notifBody" placeholder="Notification Body" value="This is a test notification">
<button id="broadcastBtn" class="btn-success">Broadcast to All</button>
<div id="broadcastStatus"></div>
</div>
<div class="section">
<h2>3. Server Stats</h2>
<button id="statsBtn" class="btn-primary">Refresh Stats</button>
<div id="statsDisplay"></div>
</div>
<div class="section">
<h2>Subscription Info</h2>
<pre id="subscriptionInfo">Not subscribed</pre>
</div>
</div>
<script>
let currentSubscription = null;
// Helper function to display status messages
function showStatus(elementId, message, type = 'info') {
const element = document.getElementById(elementId);
element.innerHTML = `<div class="status ${type}">${message}</div>`;
}
// Convert VAPID key from base64 to Uint8Array
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
return Uint8Array.from([...rawData].map(char => char.charCodeAt(0)));
}
// Get VAPID public key from server
async function getVAPIDPublicKey() {
const response = await fetch('/vapid-public-key');
const data = await response.json();
return data.publicKey;
}
// Subscribe to push notifications
async function subscribe() {
try {
const registration = await navigator.serviceWorker.ready;
const vapidPublicKey = await getVAPIDPublicKey();
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(vapidPublicKey)
});
// Send subscription to server
const response = await fetch('/subscribe', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(subscription)
});
const result = await response.json();
currentSubscription = subscription;
showStatus('subscribeStatus', '✓ Successfully subscribed!', 'success');
document.getElementById('subscriptionInfo').textContent =
JSON.stringify(subscription, null, 2);
console.log('Subscribed:', subscription);
} catch (error) {
showStatus('subscribeStatus', '✗ Subscription failed: ' + error.message, 'error');
console.error('Subscription failed:', error);
}
}
// Unsubscribe from push notifications
async function unsubscribe() {
try {
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.getSubscription();
if (subscription) {
await subscription.unsubscribe();
// Notify server
await fetch('/unsubscribe', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ endpoint: subscription.endpoint })
});
currentSubscription = null;
showStatus('subscribeStatus', '✓ Successfully unsubscribed!', 'success');
document.getElementById('subscriptionInfo').textContent = 'Not subscribed';
} else {
showStatus('subscribeStatus', 'Not currently subscribed', 'info');
}
} catch (error) {
showStatus('subscribeStatus', '✗ Unsubscribe failed: ' + error.message, 'error');
console.error('Unsubscribe failed:', error);
}
}
// Broadcast notification to all subscribers
async function broadcast() {
try {
const title = document.getElementById('notifTitle').value;
const body = document.getElementById('notifBody').value;
const response = await fetch('/broadcast', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: title,
body: body,
icon: '/icon.png'
})
});
const result = await response.json();
showStatus('broadcastStatus',
`✓ ${result.message} (Sent: ${result.sent}, Failed: ${result.failed})`,
'success');
} catch (error) {
showStatus('broadcastStatus', '✗ Broadcast failed: ' + error.message, 'error');
console.error('Broadcast failed:', error);
}
}
// Get server stats
async function getStats() {
try {
const response = await fetch('/stats');
const data = await response.json();
document.getElementById('statsDisplay').innerHTML =
`<div class="stats">Total Subscriptions: ${data.totalSubscriptions}</div>`;
} catch (error) {
showStatus('statsDisplay', '✗ Failed to fetch stats: ' + error.message, 'error');
}
}
// Check if already subscribed on page load
async function checkSubscription() {
try {
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.getSubscription();
if (subscription) {
currentSubscription = subscription;
showStatus('subscribeStatus', 'Already subscribed', 'info');
document.getElementById('subscriptionInfo').textContent =
JSON.stringify(subscription, null, 2);
}
} catch (error) {
console.error('Error checking subscription:', error);
}
}
// Event listeners
document.getElementById('subscribeBtn').addEventListener('click', subscribe);
document.getElementById('unsubscribeBtn').addEventListener('click', unsubscribe);
document.getElementById('broadcastBtn').addEventListener('click', broadcast);
document.getElementById('statsBtn').addEventListener('click', getStats);
// Register service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('Service Worker registered:', registration);
checkSubscription();
})
.catch(error => {
console.error('Service Worker registration failed:', error);
showStatus('subscribeStatus',
'✗ Service Worker registration failed', 'error');
});
} else {
showStatus('subscribeStatus', '✗ Service Workers not supported in this browser', 'error');
}
// Load initial stats
getStats();
</script>
</body>
</html>