如何将输入值从 popup.html 传递到扩展名为 chrome 的当前页面

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

我正在尝试从 popup.html 文件中获取表单的文本区域值,并将其显示在 id="demo" 的测试页面上。但由于某些原因,我没有得到任何回报。

这是我遇到的错误:Uncaught TypeError: Cannot read property 'addEventListener' of null

清单 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

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

// 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;
}

您在 chrome://extensions UI 中看到了那个错误,这是一个由您的旧错误代码引起的旧错误,它不再相关。单击那里的 clear all 按钮。

请注意,弹出窗口是一个单独的 window,因此它有自己独立的开发工具和控制台:在弹出窗口内右键单击并 select 在菜单中“检查”。

实际问题是您在网页中注入的代码(setFormInput)试图访问弹出页面中的元素,这是一个完全不同的页面。

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],
  });
});

P.S。此任务不需要 web_accessible_resourceshost_permissions