This repository has been archived by the owner on Sep 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
util.js
61 lines (55 loc) · 1.59 KB
/
util.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
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function subscribePush(registration) {
return getPublicKey().then(function (key) {
return registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: key
});
});
}
function getPublicKey() {
return fetch('./api/push/vapidpublickey')
.then(function (response) {
return response.json();
})
.then(function (data) {
return urlB64ToUint8Array(data);
});
}
function saveSubscription(subscription) {
return fetch('./api/push/subscribe', {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
subscription: subscription
})
})
.then(response => response.json())
.then(response => {
localStorage.setItem('userId', response.userId);
});
}
function deleteSubscription(subscription) {
return fetch('./api/push/unsubscribe', {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
subscription: subscription
})
});
}