从Chrome扩展弹出窗口获取值

7

我在想,如果我有一个Chrome扩展程序,当你点击图标时会弹出一个弹出窗口,并且该弹出窗口有一个文本框,用于输入数据,那么获取文本框内文本的Javascript代码会是什么样子?

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


听起来像是一个哲学问题... :) - gdoron
哈哈,也许是吧。谁知道呢。我只是在尝试弄清楚,在我的popout.js文件中,如果那个文本框的id是“input”,那么访问弹出窗口中的元素的代码将是什么。 - barndog
如果你正在寻找最简单的提示用户进行直接输入的方法,你有考虑过使用 prompt 吗? - Elias Van Ootegem
弹出窗口中的JavaScript与普通HTML页面中的JavaScript相同,有很多示例可以获取文本值 - 使用纯JavaScript或jQuery。$(“input [type ='text']”).change(function(){console.log($(this).val())}); - Stan
2个回答

12

我们可以通过绑定事件监听器获取弹出页面文本框中的值,例如在按钮的点击事件中按以下方式进行:

假设 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 
}

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


1

同样可以这样使用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,
   });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接