JavaScript Base64 Encode
To encode data in Base64, JavaScript provides a function called btoa
which is an acronym for “Binary to ASCII”. The inverse transformation is achieved by using the function atob.
Usage:
btoa(data)
- Convertsdata
toSTRING
and encodes it to Base64
Arguments:
data
(required string) - Text or binary content that you want to encode
Return Values:
STRING
- On success, it returns the Base64 value, typically longer by about 33% thandata
Exceptions:
On failure the function may throw one of the following exceptions:
InvalidCharacterError
: String contains an invalid characterTypeError
: Not enough arguments to Window.btoa
Example #1 (basic usage):
var b64 = btoa('guru');
console.log(b64); //-> "Z3VydQ=="
Example #2 (check if function is supported):
if (typeof btoa !== 'function') {
// Cannot encode data to Base64 because the btoa() function is not supported
// Perhaps you want to use a polyfill or at least inform user about this
}
Example #3 (non-string data):
// Before encoding data to Base64 the btoa() function converts it to String()
// It is for this reason that you will not get any errors if you pass a “wrong” data type
// For example, that is why in the examples below you will get the same results
btoa(null); //-> "bnVsbA=="
btoa('null'); //-> "bnVsbA=="
btoa({}); //-> "W29iamVjdCBPYmplY3Rd"
btoa('[object Object]'); //-> "W29iamVjdCBPYmplY3Rd"
btoa([0,1]); //-> "MCwx"
btoa('0,1'); //-> "MCwx"
btoa(function(){}); //-> "ZnVuY3Rpb24oKXt9"
btoa('function(){}'); //-> "ZnVuY3Rpb24oKXt9"
Example #4 (unicode string):
// By default most browsers don’t support Unicode strings
// This is why the following example throws an exception
try {
btoa('€100');
} catch (e) {
console.log(e); //-> "DOMException: String contains an invalid character"
}
For more info, check the following examples:
Comments (23)
I hope you enjoy this discussion. In any case, I ask you to join it.
Thanks in Advance,
Bharati.
var e = document.getElementById("sound")
let b64 = btoa(URL.createObjectURL(e.src))
Not sure but yeah