Skip to content

Commit 5c4810e

Browse files
author
Matt Gaunt
committed
Adding instructions on using vapid key in window
1 parent 6f57cbd commit 5c4810e

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

README.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,35 @@ a GCM API key and VAPID keys.
5656

5757
webpush.sendNotification(pushSubscription, 'Your Push Payload Text');
5858

59+
## Using VAPID Key for applicationServerKey
60+
61+
When using your VAPID key in your web app, you'll need to convert the
62+
URL safe base64 string in a Uint8Array to pass into the subscribe call,
63+
which you can do like so:
64+
65+
function urlBase64ToUint8Array(base64String) {
66+
const padding = '='.repeat((4 - base64String.length % 4) % 4);
67+
const base64 = (base64String + padding)
68+
.replace(/\-/g, '+')
69+
.replace(/_/g, '/');
70+
71+
const rawData = window.atob(base64);
72+
const outputArray = new Uint8Array(rawData.length);
73+
74+
for (let i = 0; i < rawData.length; ++i) {
75+
outputArray[i] = rawData.charCodeAt(i);
76+
}
77+
return outputArray;
78+
}
79+
80+
const vapidPublicKey = '<Your Public Key from generateVAPIDKeys()>';
81+
const convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);
82+
83+
registration.pushManager.subscribe({
84+
userVisibleOnly: true,
85+
applicationServerKey: convertedVapidKey
86+
});
87+
5988
# API Referance
6089

6190
## sendNotification(pushSubscription, payload, options)

0 commit comments

Comments
 (0)