The btoa()
method creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data).
You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the atob()
method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31.
Syntax
Parameters
-
stringToEncode
-
The binary string to encode.
Return value
An ASCII string containing the Base64 representation of stringToEncode
.
Exceptions
InvalidCharacterError
DOMException
-
The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail.
Examples
const encodedData = btoa("Hello, world");
const decodedData = atob(encodedData);
Unicode strings
Base64, by design, expects binary data as its input. In terms of JavaScript strings, this means strings in which the code point of each character occupies only one byte. So if you pass a string into btoa()
containing characters that occupy more than one byte, you will get an error, because this is not considered binary data:
const ok = "a";
console.log(ok.codePointAt(0).toString(16));
const notOK = "✓";
console.log(notOK.codePointAt(0).toString(16));
console.log(btoa(ok));
console.log(btoa(notOK));
For how to work around this limitation when dealing with arbitrary Unicode text, see The "Unicode Problem" section of the Base64 glossary entry.
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
btoa |
4 |
12 |
1 |
10 |
10.5 |
3 |
≤37 |
18 |
4 |
11 |
1 |
1.0 |
worker_support |
30 |
12 |
4 |
10 |
17 |
10 |
4.4 |
30 |
4 |
18 |
10 |
2.0 |
See also