Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Value from Chrome Extension Popup

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.

like image 408
barndog Avatar asked Nov 13 '12 07:11

barndog


1 Answers

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.

like image 169
saurabh.kg001 Avatar answered Oct 25 '22 16:10

saurabh.kg001