web-push
web-push copied to clipboard
applicationServerKey to Uint8Array
According to MDN https://developer.mozilla.org/en-US/docs/Web/API/PushManager/subscribe applicationServerKey can be either DOMString or ArrayBuffer. web-push documentation on the other hand asks to convert VAPID public key to Uint8Array using urlBase64ToUint8Array example function. I can confirm that no conversion is needed for FF 72 and Chrome 80. If this is dependent on browser provider/version, please kindly update the documentation.
PRs welcome!
After looking around, I guess this function originates from https://github.com/GoogleChromeLabs/web-push-codelab and everybody has been copying it since Google published the article. Sadly this repo is inactive and no common information source has any detailed data.
I would recommend to add an asterisk to the document stating that this function may not be necessary (any more).
No, I think at the beginning that was necessary and so both we and that repo implemented the same.
Found it. Chromium fixed the problem here: https://github.com/chromium/chromium/commit/c17c199cec7ef93693bf5ea2e573bc269c3d63b4
Good find! We'd need to test other Chromium-based browsers to see when they picked up the fix.
That's example doesn't works?
function urlBase64ToUint8Array(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;
}
const vapidPublicKey = '<Your Public Key from generateVAPIDKeys()>';
const convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);
registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: convertedVapidKey
});