• Web APIs
  • Window
  • Instance properties
    1. credentialless Experimental
    2. devicePixelRatio
    3. documentPictureInPicture Experimental
    4. event Deprecated
    5. external Deprecated
    6. fence Experimental
    7. fullScreen Non-standard
    8. innerWidth
    9. launchQueue Experimental
    10. locationbar
    11. mozInnerScreenX Non-standard
    12. mozInnerScreenY Non-standard
    13. navigation Experimental
    14. orientation Deprecated
    15. originAgentCluster Experimental
    16. performance
    17. screenLeft
    18. scrollbars
    19. scrollMaxX Non-standard
    20. scrollMaxY Non-standard
    21. sessionStorage
    22. sharedStorage Experimental
    23. status Deprecated
    24. trustedTypes
    25. atob()
    26. back() Non-standard Deprecated
    27. blur() Deprecated
    28. captureEvents() Deprecated
    29. clearImmediate() Non-standard Deprecated
    30. confirm()
    31. dump() Non-standard
    32. find() Non-standard
    33. forward() Non-standard Deprecated
    34. getDefaultComputedStyle() Non-standard
    35. getScreenDetails() Experimental
    36. moveTo()
    37. prompt()
    38. queryLocalFonts() Experimental
    39. releaseEvents() Deprecated
    40. requestFileSystem() Non-standard Deprecated
    41. scroll()
    42. scrollByLines() Non-standard
    43. scrollByPages() Non-standard
    44. setImmediate() Non-standard Deprecated
    45. setResizable() Non-standard Deprecated
    46. showDirectoryPicker() Experimental
    47. showModalDialog() Non-standard Deprecated
    48. showOpenFilePicker() Experimental
    49. showSaveFilePicker() Experimental
    50. sizeToContent() Non-standard
    51. webkitConvertPointFromNodeToPage() Non-standard Deprecated
    52. webkitConvertPointFromPageToNode() Non-standard Deprecated
  • Events
    1. beforeprint
    2. cut
    3. error
    4. hashchange
    5. messageerror
    6. orientationchange Deprecated
    7. pageswap
    8. resize
    9. scrollsnapchange Experimental
    10. scrollsnapchanging Experimental
    11. unload Deprecated
    12. vrdisplayactivate Non-standard Deprecated
    13. vrdisplayconnect Non-standard Deprecated
    14. vrdisplaydeactivate Non-standard Deprecated
    15. vrdisplaydisconnect Non-standard Deprecated
    16. vrdisplaypresentchange Non-standard Deprecated
  • Inheritance
    1. ErrorEvent
    2. HTMLBRElement
    3. HTMLCanvasElement
    4. HTMLDialogElement
    5. HTMLEmbedElement
    6. HTMLFrameSetElement Deprecated
    7. HTMLHtmlElement
    8. HTMLLIElement
    9. HTMLMapElement
    10. HTMLMeterElement
    11. HTMLOptGroupElement
    12. HTMLParagraphElement
    13. HTMLQuoteElement
    14. HTMLSpanElement
    15. HTMLTableColElement
    16. HTMLTemplateElement
    17. HTMLTrackElement
    18. HashChangeEvent
    19. MessageChannel
    20. PageRevealEvent
    21. Plugin Deprecated
    22. PluginArray Deprecated
    23. ValidityState
    24. Window interface creates a 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 Window.atob() method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31.

      Also consider using the Uint8Array.prototype.toBase64() method if your data is in a Uint8Array object to avoid creating a string containing raw bytes.

  • Syntax

    js
    btoa(stringToEncode)
    

    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

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

    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:

    js
    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(window.btoa(ok)); / YQ==
    console.log(window.btoa(notOK)); / error
    

    Since btoa interprets the code points of its input string as byte values, calling btoa on a string will cause a "Character Out Of Range" exception if a character's code point exceeds 0xff. For use cases where you need to encode arbitrary Unicode text, it is necessary to first convert the string to its constituent bytes in UTF-8, and then encode the bytes.

    The simplest solution is to use TextEncoder and TextDecoder to convert between UTF-8 and single-byte representations of the string:

    js
    function base64ToBytes(base64) {
      const binString = atob(base64);
      return Uint8Array.from(binString, (m) => m.codePointAt(0));
    }
    
    function bytesToBase64(bytes) {
      const binString = Array.from(bytes, (byte) =>
        String.fromCodePoint(byte),
      ).join("");
      return btoa(binString);
    }
    
    / Usage
    bytesToBase64(new TextEncoder().encode("a Ā 𐀀 文 🦄")); / "YSDEgCDwkICAIOaWhyDwn6aE"
    new TextDecoder().decode(base64ToBytes("YSDEgCDwkICAIOaWhyDwn6aE")); / "a Ā 𐀀 文 🦄"
    

    Converting arbitrary binary data

    The bytesToBase64 and base64ToBytes functions in the previous section can be used directly to convert between Base64 strings and Uint8Arrays.

    For better performance, asynchronous conversion between base64 data URLs is possible natively within the web platform via the fetch APIs:

    js
    async function bytesToBase64DataUrl(bytes, type = "application/octet-stream") {
      return await new Promise((resolve, reject) => {
        const reader = Object.assign(new FileReader(), {
          onload: () => resolve(reader.result),
          onerror: () => reject(reader.error),
        });
        reader.readAsDataURL(new File([bytes], "", { type }));
      });
    }
    
    async function dataUrlToBytes(dataUrl) {
      const res = await fetch(dataUrl);
      return new Uint8Array(await res.arrayBuffer());
    }
    
    / Usage
    await bytesToBase64DataUrl(new Uint8Array([0, 1, 2])); / "data:application/octet-stream;base64,AAEC"
    await dataUrlToBytes("data:application/octet-stream;base64,AAEC"); / Uint8Array [0, 1, 2]
    

    Note: For supporting environments, also consider the native Uint8Array.prototype.setFromBase64() methods.

    Specifications

    Specification
    HTML
    # dom-btoa-dev

    Browser compatibility

    BCD tables only load in the browser

    See also