I was wondering, if I had a chrome extension that had a popup when you click the icon, and that popup had a text box to input data into, what would the javascript look like to get the text inside the text box?
Update: I know how to get values from a text box but my question is, how do I specifically access the elements of my popup.html file? I tried accessed document.getElementById ect ect but that gets elements inside the actual page content, not my custom popup.
We can get the value from textbox of the popup page by binding an event listener for some event like click event of a button in the following way :
Suppose the manifest.json file is like this :
{
"manifest_version": 2,
"name": "Wonderful extension",
"description": "Wonderful extension - gets value from textbox",
"version": "1.0",
"browser_action": {
"default_icon": "images/icon.png",
"default_popup": "popup.html"
}
}
and popup.html is like this :
<!DOCTYPE html>
<html>
<head>
<title>Wonderful Extension</title>
<script src="popup.js"></script>
</head>
<body>
<div style="padding: 20px 20px 20px 20px;">
<h3>Hello,</h3>
<p>Please enter your name : </p>
<input id="name_textbox" />
<button id="ok_btn" type="button">OK</button>
</div>
</body>
</html>
then we can bind the events in the document for getting the value from textbox in the following way:
File popup.js :
document.addEventListener('DOMContentLoaded', documentEvents , false);
function myAction(input) {
console.log("input value is : " + input.value);
alert("The entered data is : " + input.value);
// do processing with data
// you need to right click the extension icon and choose "inspect popup"
// to view the messages appearing on the console.
}
function documentEvents() {
document.getElementById('ok_btn').addEventListener('click',
function() { myAction(document.getElementById('name_textbox'));
});
// you can add listeners for other objects ( like other buttons ) here
}
To access other elements of the popup page, we can use a similar approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With