6

我想知道,如果我有一个 chrome 扩展程序,当您单击图标时会弹出一个弹出窗口,并且该弹出窗口有一个用于输入数据的文本框,那么 javascript 在文本框中获取文本会是什么样子?

更新:我知道如何从文本框中获取值,但我的问题是,我如何专门访问我的 popup.html 文件的元素?我尝试访问 document.getElementById 等,但它获取实际页面内容中的元素,而不是我的自定义弹出窗口。

4

2 回答 2

11

我们可以通过以下方式为某些事件(例如按钮的单击事件)绑定事件侦听器,从弹出页面的文本框中获取值:

假设 manifest.json 文件是这样的:

{
  "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"
  } 
}

popup.html 是这样的:

<!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>

然后我们可以通过以下方式绑定文档中的事件以从文本框中获取值:

文件 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 
}

要访问弹出页面的其他元素,我们可以使用类似的方法。

于 2016-03-26T09:04:38.910 回答
0

也可以这样使用 chrome.storage.sync:

function handleButtonClick(){
   // Use stored sync value.
   chrome.storage.sync.get("textBoxValue", ({ textBoxValue }) => {
      alert(textBoxValue);
   });
}

document.getElementById("popupButton").addEventListener("click", async () => {
   let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
   
   // Store sync value before the script is executed.
   let textBoxValue = document.getElementById('textBox').value;
   chrome.storage.sync.set({ textBoxValue });

   chrome.scripting.executeScript({
       target: { tabId: tab.id },
       function: handleButtonClick,
   });
});
于 2021-03-20T02:05:26.420 回答