-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (56 loc) · 2.43 KB
/
index.js
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
// Register a Service Worker.
navigator.serviceWorker.register('service-worker.js');
navigator.serviceWorker.ready
.then(function(registration) {
// Use the PushManager to get the user's subscription to the push service.
return registration.pushManager.getSubscription()
.then(async function(subscription) {
// If a subscription was found, return it.
if (subscription) {
return subscription;
}
// Get the server's public key
const response = await fetch('./vapidPublicKey');
const vapidPublicKey = await response.text();
// Chrome doesn't accept the base64-encoded (string) vapidPublicKey yet
// urlBase64ToUint8Array() is defined in /tools.js
const convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);
// Otherwise, subscribe the user (userVisibleOnly allows to specify that we don't plan to
// send notifications that don't have a visible effect for the user).
return registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: convertedVapidKey
});
});
}).then(function(subscription) {
// Send the subscription details to the server using the Fetch API.
fetch('./register', {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
subscription: subscription
}),
});
document.getElementById('doIt').onclick = function() {
const payload = document.getElementById('notification-payload').value;
const delay = document.getElementById('notification-delay').value;
const ttl = document.getElementById('notification-ttl').value;
// Ask the server to send the client a notification (for testing purposes, in actual
// applications the push notification is likely going to be generated by some event
// in the server).
fetch('./sendNotification', {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
subscription: subscription,
payload: payload,
delay: delay,
ttl: ttl,
}),
});
};
});