简体   繁体   English

如何使用 chrome 扩展将来自 popup.html 的输入值传递到当前页面

[英]How to pass input value from popup.html to current page with a chrome extension

I'm trying to grab the textarea value of the form from the popup.html file and display it on a test page with the id="demo".我正在尝试从 popup.html 文件中获取表单的 textarea 值,并将其显示在 id="demo" 的测试页面上。 But for some reasons I'm not getting anything back.但由于某些原因,我没有得到任何回报。

Here is the error I've got: Uncaught TypeError: Cannot read property 'addEventListener' of null这是我遇到的错误: Uncaught TypeError: Cannot read property 'addEventListener' of null

Manifest V3清单 V3

{
  "name": "Test Extension",
  "version": "0.01",
  "description": "-",
 "background":{
   "service_worker": "background.js"
 },
    "permissions": ["storage", "activeTab", "scripting"],
  "host_permissions": ["<all_urls>"],
  "web_accessible_resources": [{
  "resources": ["popup.js"],
  "matches": ["<all_urls>"]
}],
  "manifest_version": 3,
    "action": {
    "default_popup": "popup.html"
  }
}

Popup.html弹出.html

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
        <form id="myForm">
            <textarea id="summary" name="summary" rows="6" cols="35">
            </textarea>
            <input id="submit" type="submit" value="Send" />
    </form>
    <script src="popup.js"></script>
  </body>
</html>

Popup.js Popup.js

// Initialize submit
let submitButton = document.getElementById("submit");
   
// When the button is clicked, inject setFormInput into current page
submitButton.addEventListener("click", async () => {
  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: setFormInput,
  });
});

// The body of this function will be executed as a content script inside the
// current page
function setFormInput() {

alert('form submitted');

var formTextarea = document.getElementById("summary").value;
document.getElementById("demo").innerText = formTextarea;
}

You see that error in chrome://extensions UI and it's an old error caused by your old incorrect code, it's no longer relevant.您在 chrome://extensions UI 中看到该错误,这是由您的旧代码不正确引起的旧错误,它不再相关。 Click the clear all button there.点击那里的clear all按钮。

Note that the popup is a separate window so it has its own separate devtools and console: right-click inside the popup and select "inspect" in the menu.请注意,弹出窗口是一个单独的 window,因此它有自己单独的开发工具和控制台:在弹出窗口内右键单击,在菜单中单击 select“检查”。

The actual problem is the code you inject in the web page (setFormInput) tries to access elements from the popup page, which is a totally different page.实际问题是您在 web 页面 (setFormInput) 中注入的代码试图从弹出页面访问元素,这是一个完全不同的页面。

The current solution for ManifestV3 in Chrome 91 and older is to use messaging to transfer a value between the pages: Chrome 91 及更早版本中 ManifestV3 的当前解决方案是使用消息传递在页面之间传递值:

submitButton.addEventListener('click', async evt => {
  evt.preventDefault(); // prevents `submit` event from reloading the popup
  const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
  await chrome.scripting.executeScript({
    target: {tabId: tab.id},
    function: setPageListener,
  });
  const text = document.getElementById('summary').value;
  chrome.tabs.sendMessage(tab.id, {id: 'demo', text}); 
});

function setPageListener() {
  chrome.runtime.onMessage.addListener(function onMessage(msg) {
    if (msg.id) {
      chrome.runtime.onMessage.removeListener(onMessage);
      document.getElementById(msg.id).textContent = msg.text;
    }
  });
}

The future solution ( since Chrome 92 ) will be the args property of executeScript:未来的解决方案自 Chrome 92 起)将是 executeScript 的args属性:

submitButton.addEventListener('click', async evt => {
  evt.preventDefault(); // prevents `submit` event from reloading the popup
  const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
  const text = document.getElementById('summary').value;
  await chrome.scripting.executeScript({
    target: {tabId: tab.id},
    func: (id, text) => {
      document.getElementById(id).textContent = text;
    },
    args: ['demo', text],
  });
});

PS There's no need for web_accessible_resources and host_permissions for this task. PS 这个任务不需要web_accessible_resourceshost_permissions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM