簡體   English   中英

如何使用 chrome 擴展將來自 popup.html 的輸入值傳遞到當前頁面

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

我正在嘗試從 popup.html 文件中獲取表單的 textarea 值,並將其顯示在 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"
  }
}

彈出.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“檢查”。

實際問題是您在 web 頁面 (setFormInput) 中注入的代碼試圖從彈出頁面訪問元素,這是一個完全不同的頁面。

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

未來的解決方案自 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 這個任務不需要web_accessible_resourceshost_permissions

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM