What is the use of window.atob() method in JS?
The atob() method
In 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.
Syntax
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.
Parameters
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 thestringthat we need to decode.
Note: It is essential to note that the parameter
string_to_decodeshould be in base64 format or encoded using thebtoa()method for this method to function correctly.
Return value
The return value of this method is of type string, representing the decoded version that is no longer in base64 encoding.
Code example
Below is a code example that will use the atob() and the btoa() methods to encode and decode a particular user input, respectively:
Explanation
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 thedecodeInput()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 thedocument.getElementById()method and assign it to a variableinput. Then we use thevalueattribute to get hold of what the reader has typed in and assign it to the variableuserinput.Line 13: We encode the user input using the
window.btoa()method and store the return value in the variableencode. Now, theencodevariable 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 variabledecode. The variabledecodenow 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 thevalueattribute, please visit the following links:
Free Resources