Skip to content

Commit b3d5e2a

Browse files
committed
Set up client-side subscription flow with VAPID keys
1 parent ecf5c6a commit b3d5e2a

File tree

2 files changed

+83
-5
lines changed

2 files changed

+83
-5
lines changed

client/index.js

Lines changed: 82 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
const client = (() => {
22
let serviceWorkerRegObj;
33
const notificationButton = document.getElementById('btn-notify');
4+
const pushButton = document.getElementById('btn-push');
5+
let isUserSubscribed = false;
46

57
const showNotificationButton = () => {
68
notificationButton.style.display = 'inline-block';
@@ -24,16 +26,16 @@ const client = (() => {
2426
};
2527

2628
const checkNotificationSupport = () => {
27-
if(!('Notification' in window)) {
28-
return Promise.reject('The browser doesn\'t support notifications.')
29+
if (!('Notification' in window)) {
30+
return Promise.reject('The browser doesn\'t support notifications.');
2931
}
3032

31-
console.log("The browser supports notifications!")
33+
console.log('The browser supports notifications!')
3234
return Promise.resolve();
3335
};
3436

3537
const registerServiceWorker = () => {
36-
if(!('serviceWorker') in navigator) {
38+
if (!('serviceWorker') in navigator) {
3739
return Promise.reject('ServiceWorker support is not available.');
3840
}
3941

@@ -42,6 +44,15 @@ const client = (() => {
4244
console.log('Service worker is registered successfully!');
4345
serviceWorkerRegObj = regObj;
4446
showNotificationButton();
47+
48+
serviceWorkerRegObj.pushManager.getSubscription()
49+
.then(subscription => {
50+
if (subscription) {
51+
disablePushNotificationButton();
52+
} else {
53+
enablePushNotificationButton();
54+
}
55+
})
4556
});
4657
};
4758

@@ -54,5 +65,71 @@ const client = (() => {
5465
checkNotificationSupport()
5566
.then(registerServiceWorker)
5667
.then(requestNotificationPermissions)
57-
.catch(err => console.error(err))
68+
.catch(err => console.error(err));
69+
70+
const disablePushNotificationButton = () => {
71+
isUserSubscribed = true;
72+
pushButton.innerText = 'DISABLE PUSH NOTIFICATIONS';
73+
};
74+
75+
const enablePushNotificationButton = () => {
76+
isUserSubscribed = false;
77+
pushButton.innerText = 'ENABLE PUSH NOTIFICATIONS';
78+
};
79+
80+
const setupPush = () => {
81+
function urlB64ToUint8Array(url) {
82+
const padding = '='.repeat((4 - url.length % 4) % 4);
83+
const base64 = (url + padding)
84+
.replace(/-/g, '+')
85+
.replace(/_/g, '/');
86+
87+
const rawData = window.atob(base64);
88+
const outputArray = new Uint8Array(rawData.length);
89+
90+
for (let i = 0; i < rawData.length; ++i) {
91+
outputArray[i] = rawData.charCodeAt(i);
92+
}
93+
94+
return outputArray;
95+
}
96+
97+
const subscribeUser = () => {
98+
const appServerPublicKey = 'BEyvjYWb29Aww8_aSq5q2qvceZwnAvvGD6uDMlOfRJCMjhxM5zZFBGZslOkl7VfwQ6MDXAyVg8SdCpixyczbqxo';
99+
const publicKeyAsArray = urlB64ToUint8Array(appServerPublicKey);
100+
101+
serviceWorkerRegObj.pushManager.subscribe({
102+
userVisibleOnly: true,
103+
applicationServerKey: publicKeyAsArray
104+
})
105+
.then(subscription => {
106+
console.log(JSON.stringify(subscription, null, 4));
107+
disablePushNotificationButton();
108+
})
109+
.catch(error => console.error('Failed to subscribe to Push Service.', error));
110+
}
111+
112+
const unSubscribeUser = () => {
113+
console.log('unsubscribing user');
114+
115+
serviceWorkerRegObj.pushManager.getSubscription()
116+
.then(subscription => {
117+
if (subscription) {
118+
return subscription.unsubscribe();
119+
}
120+
})
121+
.then(enablePushNotificationButton)
122+
.catch(error => console.error('Failed to unsubscribe from Push Service.', error));
123+
}
124+
125+
pushButton.addEventListener('click', () => {
126+
if (isUserSubscribed) {
127+
unSubscribeUser();
128+
} else {
129+
subscribeUser();
130+
}
131+
})
132+
};
133+
134+
setupPush();
58135
})();

index.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
<main>
1414
<h1>Web Push Notifications</h1>
1515
<button id="btn-notify" class="notification-btn">SEND NOTIFICATION</button>
16+
<button id="btn-push">ENABLE PUSH NOTIFICATIONS</button>
1617

1718
<script src="client/index.js"></script>
1819
</main>

0 commit comments

Comments
 (0)