我正在学习如何构建谷歌浏览器扩展程序。我在一个网页上有一个联系表单,我正在用它进行测试。我试图创建一个扩展程序,可以读取该表单中的输入字段值。目前为止,我拥有:
manifest.json
{
"manifest_version": 2,
"name": "Contact Form Friend",
"description": "This extension gets contact form info.",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"<all_urls>"
]
}
弹出窗口.html
<!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>
<style type="text/css">
body {
margin: 10px;
white-space: nowrap;
}
h1 {
font-size: 15px;
}
#container {
align-items: center;
display: flex;
justify-content: space-between;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<h1>Info</h1>
<div id="info">
</div>
</body>
</html>
弹出框.js
function getHost() {
return document.documentElement;
}
document.addEventListener('DOMContentLoaded', () => {
const infoDisplay = document.getElementById('info');
const scriptToRun = `(${getHost})()`;
// Run the script in the context of the tab
chrome.tabs.executeScript({
code: scriptToRun
}, (result) => {
var values = [];
var inputFields = result.getElementsByTagName('input');
infoDisplay.innerHTML = 'inputs: ' + inputFields.length;
for (var i = 0; i < inputFields.length; i++) {
values.push(inputFields[i].value);
}
infoDisplay.innerHTML += '<br />fields: ' + values.length;
});
});
当我运行此代码时,它似乎无法访问用户所在的网页(而不是扩展程序的网页)中的输入字段。我做错了什么?我缺少权限吗?我不这么认为。然而,它没有起作用,我也不确定原因。谢谢您的帮助。