我对Chrome扩展程序还很陌生,因此我决定制作一个。现在,我需要访问页面中的表,其中有多少表,我已经可以通过分别使用控制台执行$(document).find("table")
和$(document).find("table").length
从文档中实现,但是,我尝试chrome.tabs.getCurrent
了扩展等,但是我找不到方法从扩展名访问此数据。有什么帮助吗?
这是我的代码:
popup.js:
var numOfTables = 0;
function getNumOfTables() {
chrome.tabs.getCurrent(function(tab) {
alert($(document).find("table").length);
var tablesResult = $(document).find("table").length;
numOfTables = tablesResult;
$("#mainParagraph").text("We found " + numOfTables + " in this page");
});
};
getNumOfTables();
popup.html:
<!doctype html>
<!--
This page is shown when the extension button is clicked, because the
"browser_action" field in manifest.json contains the "default_popup" key with
value "popup.html".
-->
<html>
<head>
<title>Getting Started Extension's Popup</title>
<style>
body {
font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif;
font-size: 100%;
}
#status {
/* avoid an excessively wide status text */
white-space: pre;
text-overflow: ellipsis;
overflow: hidden;
max-width: 400px;
}
</style>
<!--
- JavaScript and HTML must be in separate files: see our Content Security
- Policy documentation[1] for details and explanation.
-
- [1]: https://developer.chrome.com/extensions/contentSecurityPolicy
-->
<script src="popup.js"></script>
</head>
<body>
<h2 id="header">HTML Table to Excel</h2>
<p id="mainParagraph"></p>
</body>
</html>
我真的不需要任何复杂的东西,只需要一种方法即可$(document).find("table")
从扩展名的当前选项卡中执行并获取结果,executeScript应该可以工作,但是我认为它不能返回函数的值。提前致谢
因此,您正在尝试访问当前选项卡。
chrome.tabs.getCurrent(function(tab) {
/* and you are not using tab! */
});
仅运行此命令就不会神奇地引用该选项卡。document
仍然指popup.html
,因此您什么也找不到。
查看体系结构概述以了解为什么需要内容脚本。
因此,您需要使用注入内容脚本,executeScript
并以某种方式将结果报告回来。消息传递将帮助您。
您还需要包括自己的jQuery副本以使用$
,因为它是与页面不同的上下文。
首先,您需要权限。如果您要从弹出窗口中插入当前选项卡,"activeTab"
就足够了。
然后,您可以注入以下内容:
// popup.js
chrome.tabs.executeScript(
null, // Current tab
{file: "jquery.js"}, // Script to inject
function() { // Something to do afterwards
chrome.tabs.executeScript(null, {file: "content.js"}, afterInject);
}
);
在内容脚本中,准备好回答查询。
// content.js
// Ensure it's injected only once
var injected;
if(!injected) {
injected = true;
chrome.runtime.onMessage.addListener(handleMessage);
}
function handleMessage(message, sender, sendResponse) {
switch(message.action) {
case "getNumOfTables":
sendResponse($(document).find("table").length);
default:
console.error("Unknown request from extension");
}
}
最后,您可以从弹出窗口中发送一条消息来请求此操作:
// Make sure it happens after the inject
function afterInject(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {action: "getNumOfTables"}, function(result) {
// Use the result here
});
});
}
不知道该代码是否会有用,无需深入说明,但这只是一个起点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句