Skip to content

Instantly share code, notes, and snippets.

@Klerith
Last active October 31, 2024 14:34
Show Gist options
  • Save Klerith/80abd742d726dd587f4bd5d6a0ab26b6 to your computer and use it in GitHub Desktop.
Save Klerith/80abd742d726dd587f4bd5d6a0ab26b6 to your computer and use it in GitHub Desktop.
web-push: urlBase64ToUint8array
// Web-Push
// Public base64 to Uint
function urlBase64ToUint8Array(base64String) {
var padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
var rawData = window.atob(base64);
var outputArray = new Uint8Array(rawData.length);
for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
@Selvam6994
Copy link

Throws an error => Uncaught (in promise) ReferenceError: window is not defined
at urlBase64ToUint8Array

@py660
Copy link

py660 commented Sep 2, 2024

Throws an error => Uncaught (in promise) ReferenceError: window is not defined at urlBase64ToUint8Array

Instead of window.atob(base64), you can use something like Buffer.from(base64, 'base64').toString() assuming that you're trying to use node.js.

@jowo-io
Copy link

jowo-io commented Oct 31, 2024

Throws an error => Uncaught (in promise) ReferenceError: window is not defined at urlBase64ToUint8Array

Instead of window.atob(base64), you can use something like Buffer.from(base64, 'base64').toString() assuming that you're trying to use node.js.

here's an example:

function urlBase64ToUint8Array(base64String: string) {
  const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
  const base64 = (base64String + padding)
    .replace(/\\-/g, "+")
    .replace(/_/g, "/");
  return Buffer.from(base64, "base64");
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment