Som*_*ser 10 javascript google-chrome google-chrome-extension
我正在努力学习如何构建Google Chrome扩展程序.我在网页上有一个联系表单,我正在用它进行测试.我正在尝试创建一个扩展,它将从该表单中读取输入字段值.这时,我有:
的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>"
]
}
Run Code Online (Sandbox Code Playgroud)
popup.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>
Run Code Online (Sandbox Code Playgroud)
popup.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;
});
});
Run Code Online (Sandbox Code Playgroud)
当我运行它时,它就像无法访问用户所在网页的输入字段(而不是扩展程序的网页).我究竟做错了什么?我错过了许可吗?我不相信.但是,它不起作用,我不知道为什么.
谢谢您的帮助.
据Gabriel Bleu报道,您需要一个内容脚本才能与Chrome标签中的网页进行交互。
以下是Chrome扩展程序的示例,其中内容脚本向popup.js公开了两个“命令”。
请参阅代码注释以获取解释。
manifest.json(类似于您的清单)
{
"name": "My ext",
"version": "0.1",
"description": "my desc",
"permissions": [
"activeTab",
"<all_urls>"
],
"icons": {
"128": "icon-128.png"
},
"browser_action": {
"default_title": "My ext",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"manifest_version": 2,
"content_security_policy": "script-src 'self' https://ajax.googleapis.com object-src 'self'"
}
Run Code Online (Sandbox Code Playgroud)
popup.html(类似于jQuery,只是为了方便DOM操作而使用jQuery)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="application/javascript" charset="utf-8" src="popup.js"></script>
</head>
<body class="body-popup">
<button id="btn_check" class="btn btn-warning">check current tab</button>
<hr>
<div id="pg_url"></div>
<hr>
<div id="log"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
popup.js
$(function() {
$('#btn_check').click(function() { checkCurrentTab(); });
});
function checkCurrentTab() {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var url = tabs[0].url;
console.log("checkCurrentTab: "+url);
$(".pg_url").text(url);
// request content_script to retrieve title element innerHTML from current tab
chrome.tabs.sendMessage(tabs[0].id, "getHeadTitle", null, function(obj) {
console.log("getHeadTitle.from content_script:", obj);
log("from content_script:"+obj);
});
});
}
document.addEventListener('DOMContentLoaded', function () {
chrome.windows.getCurrent(function (currentWindow) {
chrome.tabs.query({active: true, windowId: currentWindow.id}, function(activeTabs) {
// inject content_script to current tab
chrome.tabs.executeScript(activeTabs[0].id, {file: 'content_script.js', allFrames: false});
});
});
});
function log(txt) {
var h = $("#log").html();
$("#log").html(h+"<br>"+txt);
}
Run Code Online (Sandbox Code Playgroud)
content_script.js
// you will see this log in console log of current tab in Chrome when the script is injected
console.log("content_script.js");
chrome.runtime.onMessage.addListener(function(cmd, sender, sendResponse) {
console.log("chrome.runtime.onMessage: "+cmd);
switch(cmd) {
case "getHtml":
// retrieve document HTML and send to popup.js
sendResponse({title: document.title, url: window.location.href, html: document.documentElement.innerHTML});
break;
case "getHeadTitle":
// retrieve title HTML and send to popup.js
sendResponse(document.getElementsByTagName("title")[0].innerHTML);
break;
default:
sendResponse(null);
}
});
Run Code Online (Sandbox Code Playgroud)
PS:显然jQuery不是强制性的
这是您收到的错误:
Error in response to tabs.executeScript: TypeError: result.getElementsByTagName is not a function
at Object.chrome.tabs.executeScript [as callback] (chrome-extension://lmaefdnejmkjjmgalgfofdbobhapfmoh/popup.js:15:32)
at HTMLDocument.document.addEventListener (chrome-extension://lmaefdnejmkjjmgalgfofdbobhapfmoh/popup.js:10:17)
Run Code Online (Sandbox Code Playgroud)
我建议不要尝试在 popup.js 中获取当前选项卡的 DOM,而是使用内容脚本来执行任务并将结果作为消息发送到弹出窗口。
清单.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>"
],
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["content.js"]
}
]
}
Run Code Online (Sandbox Code Playgroud)
在manifest.json文件中,您必须添加内容脚本并设置要注入脚本的站点的URL。
弹出窗口.js
document.addEventListener('DOMContentLoaded', () => {
const infoDisplay = document.getElementById('info');
window.addEventListener('DOMContentLoaded', function () {
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {}, function (result) {
infoDisplay.innerHTML = result
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
在popup.js中,向内容脚本发送请求,以获取输入字段的数量并将响应插入到div.
内容.js
chrome.runtime.onMessage.addListener(function (msg, sender, response) {
var values = [];
var inputFields = document.getElementsByTagName('input');
var result = 'inputs: ' + inputFields.length;
for (var i = 0; i < inputFields.length; i++) {
values.push(inputFields[i].value);
}
result += '<br />fields: ' + values.length;
response(result)
});
Run Code Online (Sandbox Code Playgroud)
创建一个新文件,命名为content.js. 该文件将被注入到网页中,并侦听来自 popup.js 的消息。当消息到达时,它会计算响应并将其发送回 popup.js。
要了解有关内容脚本的更多信息,请查看文档。
如果您的扩展需要与网页交互,那么它需要一个内容脚本。内容脚本是在已加载到浏览器中的页面上下文中执行的一些 JavaScript。将内容脚本视为已加载页面的一部分,而不是与其打包的扩展(其父扩展)的一部分。
https://developer.chrome.com/docs/extensions/mv3/content_scripts/
| 归档时间: |
|
| 查看次数: |
7121 次 |
| 最近记录: |