WindowOrWorkerGlobalScope.btoa() method creates a Base64 -encoded ASCII string from a binary string (i.e., a 字符串 object 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.

句法

var encodedData = scope.btoa(stringToEncode);
					

参数

stringToEncode
binary string to encode.

返回值

An ASCII string containing the Base64 representation of stringToEncode .

异常

InvalidCharacterError

The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail.

范例

const encodedData = window.btoa('Hello, world'); // encode a string
const decodedData = window.atob(encodedData); // decode the string
					

Unicode strings

btoa() function takes a JavaScript string as a parameter. In JavaScript strings are represented using the UTF-16 character encoding: in this encoding, strings are represented as a sequence of 16-bit (2 byte) units. Every ASCII character fits into the first byte of one of these units, but many other characters don't.

Base64, by design, expects binary data as its input. In terms of JavaScript strings, this means strings in which 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)); //   61: occupies < 1 byte
const notOK = "✓"
console.log(notOK.codePointAt(0).toString(16)); // 2713: occupies > 1 byte
console.log(btoa(ok));    // YQ==
console.log(btoa(notOK)); // error
					

If you need to encode Unicode text as ASCII using btoa() , one option is to convert the string such that each 16-bit unit occupies only one byte. For example:

// convert a Unicode string to a string in which
// each 16-bit unit occupies only one byte
function toBinary(string) {
  const codeUnits = new Uint16Array(string.length);
  for (let i = 0; i < codeUnits.length; i++) {
    codeUnits[i] = string.charCodeAt(i);
  }
  return String.fromCharCode(...new Uint8Array(codeUnits.buffer));
}
// a string that contains characters occupying > 1 byte
const myString = "☸☹☺☻☼☾☿";
const converted = toBinary(myString);
const encoded = btoa(converted);
console.log(encoded);                 // OCY5JjomOyY8Jj4mPyY=
					

If you do this, of course you'll have to reverse the conversion on the decoded string:

function fromBinary(binary) {
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < bytes.length; i++) {
    bytes[i] = binary.charCodeAt(i);
  }
  return String.fromCharCode(...new Uint16Array(bytes.buffer));
}
const decoded = atob(encoded);
const original = fromBinary(decoded);
console.log(original);                // ☸☹☺☻☼☾☿
					

Polyfill

You can use a polyfill from https://github.com/MaxArt2501/base64-js/blob/master/base64.js for browsers that don't support it.

规范

规范 状态 注释
HTML 实时标准
The definition of 'WindowOrWorkerGlobalScope.btoa()' in that specification.
实时标准 Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
HTML 5.1
The definition of 'WindowBase64.btoa()' in that specification.
推荐 快照 HTML 实时标准 . No change.
HTML5
The definition of 'WindowBase64.btoa()' in that specification.
推荐 快照 HTML 实时标准 。创建 WindowBase64 (properties where on the target before it).

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
btoa Chrome 4 Edge 12 Firefox 1
1
52 注意事项
btoa() now defined on WindowOrWorkerGlobalScope 混合。
IE 10 Opera 10.5 Safari 3 WebView Android ≤37 Chrome Android 18 Firefox Android 4
4
52 注意事项
atob() now defined on WindowOrWorkerGlobalScope 混合。
Opera Android 11 Safari iOS 1 Samsung Internet Android 1.0

图例

完整支持

完整支持

见实现注意事项。

另请参阅

元数据

  • 最后修改:
  1. WindowOrWorkerGlobalScope
  2. 特性
    1. caches
    2. crossOriginIsolated
    3. indexedDB
    4. isSecureContext
    5. origin
  3. 方法
    1. atob()
    2. btoa()
    3. clearInterval()
    4. clearTimeout()
    5. createImageBitmap()
    6. fetch()
    7. queueMicrotask()
    8. setInterval()
    9. setTimeout()
  4. 实现通过:
    1. Window
    2. WorkerGlobalScope
  5. HTML DOM 相关页面
    1. BeforeUnloadEvent
    2. DOMStringMap
    3. ErrorEvent
    4. GlobalEventHandlers
    5. HTMLAnchorElement
    6. HTMLAreaElement
    7. HTMLAudioElement
    8. HTMLBRElement
    9. HTMLBaseElement
    10. HTMLBaseFontElement
    11. HTMLBodyElement
    12. HTMLButtonElement
    13. HTMLCanvasElement
    14. HTMLContentElement
    15. HTMLDListElement
    16. HTMLDataElement
    17. HTMLDataListElement
    18. HTMLDialogElement
    19. HTMLDivElement
    20. HTMLDocument
    21. HTMLElement
    22. HTMLEmbedElement
    23. HTMLFieldSetElement
    24. HTMLFormControlsCollection
    25. HTMLFormElement
    26. HTMLFrameSetElement
    27. HTMLHRElement
    28. HTMLHeadElement
    29. HTMLHeadingElement
    30. HTMLHtmlElement
    31. HTMLIFrameElement
    32. HTMLImageElement
    33. HTMLInputElement
    34. HTMLIsIndexElement
    35. HTMLKeygenElement
    36. HTMLLIElement
    37. HTMLLabelElement
    38. HTMLLegendElement
    39. HTMLLinkElement
    40. HTMLMapElement
    41. HTMLMediaElement
    42. HTMLMetaElement
    43. HTMLMeterElement
    44. HTMLModElement
    45. HTMLOListElement
    46. HTMLObjectElement
    47. HTMLOptGroupElement
    48. HTMLOptionElement
    49. HTMLOptionsCollection
    50. HTMLOutputElement
    51. HTMLParagraphElement
    52. HTMLParamElement
    53. HTMLPictureElement
    54. HTMLPreElement
    55. HTMLProgressElement
    56. HTMLQuoteElement
    57. HTMLScriptElement
    58. HTMLSelectElement
    59. HTMLShadowElement
    60. HTMLSourceElement
    61. HTMLSpanElement
    62. HTMLStyleElement
    63. HTMLTableCaptionElement
    64. HTMLTableCellElement
    65. HTMLTableColElement
    66. HTMLTableDataCellElement
    67. HTMLTableElement
    68. HTMLTableHeaderCellElement
    69. HTMLTableRowElement
    70. HTMLTableSectionElement
    71. HTMLTemplateElement
    72. HTMLTextAreaElement
    73. HTMLTimeElement
    74. HTMLTitleElement
    75. HTMLTrackElement
    76. HTMLUListElement
    77. HTMLUnknownElement
    78. HTMLVideoElement
    79. HashChangeEvent
    80. 历史
    81. ImageData
    82. 定位
    83. MessageChannel
    84. MessageEvent
    85. MessagePort
    86. Navigator
    87. NavigatorGeolocation
    88. NavigatorID
    89. NavigatorLanguage
    90. NavigatorOnLine
    91. NavigatorPlugins
    92. PageTransitionEvent
    93. Plugin
    94. PluginArray
    95. PopStateEvent
    96. PortCollection
    97. PromiseRejectionEvent
    98. RadioNodeList
    99. Transferable
    100. ValidityState
    101. Window
    102. WindowBase64
    103. WindowEventHandlers
    104. WindowTimers