web-push icon indicating copy to clipboard operation
web-push copied to clipboard

applicationServerKey to Uint8Array

Open PRR24 opened this issue 4 years ago • 6 comments

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.

PRR24 avatar Mar 02 '20 11:03 PRR24

PRs welcome!

marco-c avatar Mar 03 '20 00:03 marco-c

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).

PRR24 avatar Mar 03 '20 11:03 PRR24

No, I think at the beginning that was necessary and so both we and that repo implemented the same.

marco-c avatar Mar 03 '20 12:03 marco-c

Found it. Chromium fixed the problem here: https://github.com/chromium/chromium/commit/c17c199cec7ef93693bf5ea2e573bc269c3d63b4

PRR24 avatar Mar 04 '20 09:03 PRR24

Good find! We'd need to test other Chromium-based browsers to see when they picked up the fix.

marco-c avatar Mar 05 '20 10:03 marco-c

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
});

Yagasaki7K avatar Jun 08 '21 14:06 Yagasaki7K