What is the use of the window.btoa() method in JavaScript?
The window.btoa() method in JavaScript
In this Answer, we will look at the btoa() method of the window object. This method encodes a particular string of our choice in the
Syntax
window.btoa(string_to_encode)
Here, a window object refers to an open window in our browser.
Parameters
This method takes the following parameter:
string_to_encode: This variable contains the string we want to encode in base-64 format. It is a required attribute.
Return value
The return value of this method is a string, which is in the base-64 format.
Note: The characters used by the
window.btoa()method to encode a particular string are "A–Z," "a–z," "0–9," "+," "/, " and "=." The return value from the method will always be a combination of the character sequences listed above.
Code
The code example below uses this method and converts a particular string of our choice into the base-64 format:
Explanation
Lines 5–10: This code contains a
<div>tag that encapsulates the content of our web page. Some of the essential HTML elements that demonstrate the functionality of the method are as follows:Line 8: Here, we have a
<input>field that will take the input from the reader for the string they want to encode.Line 9: This line renders an HTML
<button>listening for theonclickevent and triggers theencode()method.
Lines 12–16: In these lines, our
encode()method is enclosed within HTML<script>tags. The body of the method is composed of the following instructions:Line 13: First, we fetch our
<input>field using thedocument.getElementById()method. Thevalueattribute will then help retrieve the user input and assign it to the variableinput.Line 14: We use the
inputvariable and give it as a parameter towindow.btoa()method. The return value we get is assigned to the variablebase64. So now,base64contains our encoded string.Line 15: Here, we use Javascript's
alert()method to display the encoded string to the reader. Please refer to this Answer to read more on thealert()method.
Note: To read more on the
valueattribute anddocument.getElementById()method, please refer to the following links:
Free Resources