atob()
methodIn this Answer, we will look at the atob()
method of the window object. This method provides us with a decoded string that was previously encoded using window.btoa()
method in
This Answer will cover all the necessary details regarding the syntax and parameters for this method.
Read more on the
window.btoa()
method in this Answer.
Now that we are familiar with the use of this method, let us explore its syntax:
window.atob(string_to_decode);
Here, window
refers to an open window in our browser.
The parameter that is required to test the working of this method is the following:
string_to_decode
: This is a required parameter that specifies the string
that we need to decode.
Note: It is essential to note that the parameter
string_to_decode
should be in base64 format or encoded using thebtoa()
method for this method to function correctly.
The return value of this method is of type string
, representing the decoded version that is no longer in base64 encoding.
Below is a code example that will use the atob()
and the btoa()
methods to encode and decode a particular user input, respectively:
The description for the code in the example above is as follows:
Lines 5–8: In these lines of code, we have our <div>
tag that encapsulates the content of our web page. The content of the web page is composed of the following HTML elements:
Line 6: This line contains an <input>
field, where the user specifies the string they want to decode.
Line 7: Here, we have a <button>
, which fires the decodeInput()
method that we define later in the <script>
tags.
Lines 10–18: These lines contain our decodeInput()
method, which is composed of the instructions mentioned below:
Lines 11–12: We fetch <input>
using the document.getElementById()
method and assign it to a variable input
. Then we use the value
attribute to get hold of what the reader has typed in and assign it to the variable userinput
.
Line 13: We encode the user input using the window.btoa()
method and store the return value in the variable encode
. Now, the encode
variable contains our user input in base64 format.
Line 16: We use the window.atob()
method to get back to our original user input and store the return value in the variable decode
. The variable decode
now contains the initial user input that we first encoded.
Lines 14–16: These statements are simple console.log()
statements that display the encoded and decoded versions of the user input.
To read more on
document.getElementById()
method and thevalue
attribute, please visit the following links:
Free Resources