-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.js
67 lines (59 loc) · 1.97 KB
/
client.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
63
64
65
66
67
window.addEventListener('load', () => {
initServiceWorker();
updatePrompt();
});
//------------------------------------------------------------------------
// Notification Prompt
//------------------------------------------------------------------------
function updatePrompt() {
if ('Notification' in window) {
if (Notification.permission == 'granted' || Notification.permission == 'denied') {
promptLink.style.display = 'none';
} else {
promptLink.style.display = 'block';
}
}
}
function onPromptClick() {
if ('Notification' in window) {
Notification.requestPermission().then((permission) => {
updatePrompt();
if (permission === 'granted') {
console.log('Notification permission granted.');
init();
} else if (permission === 'denied') {
console.warn('Notification permission denied.');
}
});
}
}
//------------------------------------------------------------------------
// Init Service Worker
//------------------------------------------------------------------------
const vapidPublicKey = VAPID_PUBLIC_KEY;
async function initServiceWorker() {
if ('serviceWorker' in navigator) {
const swRegistration = await navigator.serviceWorker.register('sw.js');
const subscription = await swRegistration.pushManager.getSubscription();
if (subscription) {
console.log('User is already subscribed:', subscription);
sendSubscriptionToServer(subscription);
} else {
const subscription = await swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: vapidPublicKey
});
console.log('User subscribed:', subscription);
sendSubscriptionToServer(subscription);
}
} else {
console.warn('Service worker is not supported');
}
}
function sendSubscriptionToServer(subscription) {
fetch('/subscribe', {
method: 'post',
body: JSON.stringify(subscription),
headers: { 'content-type': 'application/json' }
});
}