我制作了一个非常简单的 Chrome 扩展程序,其中应该发生的是用户可以在文本框中输入一个值,按下按钮,然后将输入的值填充到页面文本框(或任何其他元素)中。
所以,我有
popup.html:
<!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>
<script src="popup.js"></script>
</head>
<body>
<textarea type="text" id="data-details" cols="40" rows="5"></textarea>
<input type="button" id="btn-fill" value="Fill" />
</body>
</html>
popup.js:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("btn-fill").addEventListener("click", injectTheScript);
});
function injectTheScript() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.executeScript(tabs[0].id, { file: "content_script.js" });
});
}
content_script.js:
function fillElements()
{
var dataDetailsStr = document.getElementById("data-details").value;
// error here : Uncaught TypeError: Cannot read property 'value' of null
document.getElementById("txt-page-input").value = dataDetailsStr;
}
fillElements();
manifest.json:
{
"manifest_version": 2,
"name": "Fill Data",
"description": "Fills data on the page",
"version": "1.0",
"permissions": [
"activeTab",
"http://*/*"
],
"browser_action": {
"default_icon": "img/icon.png",
"default_popup": "popup.html"
},
"content_scripts": [{
"matches": ["http://*/*"],
"js": ["jquery.js", "content_script.js"]
}]
}
document.getElementById ("data-details")
始终返回 null
。如何访问这个元素,或者如何正确编写这个元素?我是新手。
最佳答案
问题在于 document.getElementById("data-details")
位于注入(inject)的脚本中,并且浏览器搜索具有 id data-details
的对象在页面中,而不是在 popup.html
中
所以
popup.js
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("btn-fill").addEventListener("click", injectTheScript);
});
function injectTheScript() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.executeScript(tabs[0].id, { file: "content_script.js" });
chrome.tabs.sendMessage(tabs[0].id, document.getElementById("data-details").value);
});
}
content_script.js
function fillElements()
{
chrome.runtime.onMessage.addListener(function(message) {
document.getElementById("txt-page-input").value = message;
});
}
fillElements();
关于javascript - 如何从弹出的 DOM 中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42678531/