javascript - 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". 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
Manifest 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
那里的按钮。
请注意,弹出窗口是一个单独的窗口,因此它有自己独立的开发工具和控制台:在弹出窗口内右键单击并在菜单中选择“检查”。
实际问题是您在网页中注入的代码 (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 起)将是args
executeScript 的属性:
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_resources
和host_permissions
这个任务。