我知道很多帖子都问过这个问题,但老实说我不明白。我是 JavaScript、Chrome 扩展和所有东西的新手,我有这个课程作业。所以我需要制作一个插件,使用跨域请求对任何给定页面上的 DOM 对象进行计数。到目前为止,我已经能够使用 Chrome Extension API 实现这一点。现在的问题是我需要在 popup.html 页面上显示来自 contentScript.js 文件的数据。我不知道该怎么做我已经尝试阅读文档但是在 chrome 中发送消息我只是不明白该怎么做。
以下是到目前为止的代码。
清单.json
{
"manifest_version":2,
"name":"Dom Reader",
"description":"Counts Dom Objects",
"version":"1.0",
"page_action": {
"default_icon":"icon.png",
"default_title":"Dom Reader",
"default_popup":"popup.html"
},
"background":{
"scripts":["eventPage.js"],
"persistent":false
},
"content_scripts":[
{
"matches":["http://pluralsight.com/training/Courses/*", "http://pluralsight.com/training/Authors/Details/*", "https://www.youtube.com/user/*", "https://sites.google.com/site/*", "http://127.0.0.1:3667/popup.html"],
"js":["domReader_cs.js","jquery-1.10.2.js"]
//"css":["pluralsight_cs.css"]
}
],
"permissions":[
"tabs",
"http://pluralsight.com/*",
"http://youtube.com/*",
"https://sites.google.com/*",
"http://127.0.0.1:3667/*"
]
弹出窗口.html
<!doctype html>
<html>
<title> Dom Reader </title>
<script src="jquery-1.10.2.js" type="text/javascript"></script>
<script src="popup.js" type="text/javascript"></script>
<body>
<H1> Dom Reader </H1>
<input type="submit" id="readDom" value="Read DOM Objects" />
<div id="domInfo">
</div>
</body>
</html>
事件页面.js
var value1,value2,value3;
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.action == "show") {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.pageAction.show(tabs[0].id);
});
}
value1 = request.tElements;
});
弹窗.js
$(function (){
$('#readDom').click(function(){
chrome.tabs.query({active: true, currentWindow: true}, function (tabs){
chrome.tabs.sendMessage(tabs[0].id, {action: "readDom"});
});
});
});
内容脚本
var totalElements;
var inputFields;
var buttonElement;
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse){
if(request.action == "readDom"){
totalElements = $("*").length;
inputFields = $("input").length;
buttonElement = $("button").length;
}
})
chrome.runtime.sendMessage({
action: "show",
tElements: totalElements,
Ifields: inputFields,
bElements: buttonElement
});
任何帮助将不胜感激,请避免我做的任何傻事:)
原文由 Sumair Baloch 发布,翻译遵循 CC BY-SA 4.0 许可协议
尽管您绝对是在正确的方向上(并且实际上已经接近尾声),但您的代码中存在一些(imo)不良做法(例如,为这样一个微不足道的任务注入整个库(jquery),声明不必要的权限,使多余的调用 API 方法等)。
我自己没有测试你的代码,但从快速概览来看,我相信更正以下内容可能会产生一个有效的解决方案(虽然不是很接近最佳):
(强调我的)
onMessage
侦听器回调中。也就是说,这是我提出的方法:
控制流:
目录结构:
清单.json:
背景.js:
内容.js:
popup.js:
popup.html: