-
Notifications
You must be signed in to change notification settings - Fork 0
/
notification.js
72 lines (65 loc) · 1.87 KB
/
notification.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
68
69
70
71
72
const isPushSupported = () => {
//checks if user has granted permission to Push notifications
if (Notification.permission === 'denied') {
alert('User has blocked push notification.');
return;
}
//Checks if current browser supports Push notification
if (!('PushManager' in window)) {
alert("Sorry, Push notification isn't supported in your browser.");
return;
}
//Get `push notification` subscription id
//If `serviceWorker` is registered and ready
navigator.serviceWorker.ready.then(function (registration) {
registration.pushManager.getSubscription().catch(function (error) {
console.error('Error occurred while enabling push ', error);
});
});
};
const subscribePush = () => {
//Subscribes user to Push notifications
registration.pushManager
.subscribe({
userVisibleOnly: true, //Set user to see every notification
})
.then(function (subscription) {
toast('Subscribed successfully.');
console.info('Push notification subscribed.');
console.log(subscription);
})
.catch(function (error) {
console.error('Push notification subscription error: ', error);
});
};
const unsubscribePush = () => {
navigator.serviceWorker.ready.then(function (registration) {
//Get subscription
registration.pushManager
.getSubscription()
.then(function (subscription) {
//If no `push subscription`, then return
if (!subscription) {
alert('Unable to unregister push notification.');
return;
}
//Unsubscribes user
subscription
.unsubscribe()
.then(function () {
toast('Unsubscribed successfully.');
console.info('Push notification unsubscribed.');
})
.catch(function (error) {
console.error(error);
});
})
.catch(error => {
console.error('Failed to unsubscribe push notification.');
});
});
};
window.addEventListener('load', () => {
isPushSupported();
console.log('hello');
});