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
window.btoa(string_to_encode)
Here, a window
object refers to an open window in our browser.
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.
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.
The code example below uses this method and converts a particular string of our choice into the base-64 format:
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 the onclick
event and triggers the encode()
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 the document.getElementById()
method. The value
attribute will then help retrieve the user input and assign it to the variable input
.
Line 14: We use the input
variable and give it as a parameter to window.btoa()
method. The return value we get is assigned to the variable base64
. So now, base64
contains 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 the alert()
method.
Note: To read more on the
value
attribute anddocument.getElementById()
method, please refer to the following links:
Free Resources