JavaScript Window atob() Global Method

JavaScript Window atob() method is used to decode a string of data encoded using Base64 encoding.

Syntax

atob(encodedData)

Parameters

encodedData: It is a binary string (i.e., a string in which each character is treated as a byte of binary data) containing base64-encoded data.

Return value

It is an ASCII string containing decoded data from encodedData.

Exceptions

InvalidCharacterError DOMException: Thrown if encodedData is not valid base64.

Example 1: Basic Decoding

In this example, we’ll simply decode a base-64 encoded string to get its original value.

// Base-64 encoded string
let encodedString = "SGVsbG8gV29ybGQh";

// Decoding the string
let decodedString = atob(encodedString);

console.log(decodedString);

Output

Hello World!

Example 2: Decoding User Input

In this example, we’ll decode a base-64 encoded string from the user.

// Taking encoded string as input from the user
let encodedUserInput = prompt("Enter a base-64 encoded string:");

// Decoding the string
let decodedUserInput = atob(encodedUserInput);

alert("Decoded String: " + decodedUserInput);

Output

If you input SGVsbG8gV29ybGQh (which is “Hello World!” in base-64), the alert will display “Decoded String: Hello World!”.

If you input a string that’s not valid base-64, you might get unexpected results or errors.

Example 3: Using atob() in HTML

In this example, we will decode a base-64 encoded string and display it in an HTML element.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>atob() Example</title>
</head>

<body>
  <button onclick="decodeString()">Decode</button>
  <p id="decodedOutput"></p>

  <script>
    function decodeString() {
      let encodedString = "U29tZSBiYXNlLTY0IGVuY29kZWQgc3RyaW5n";
      let decodedString = atob(encodedString);
      document.getElementById("decodedOutput").innerText = decodedString;
    }
 </script>
</body>
</html>

Output

Using atob() in HTML

Browser Support

Chrome IE Edge Firefox Safari Opera
Yes 10-11 Yes Yes Yes Yes

That’s it!