我有一个chrome扩展。我需要从当前页面的HTML源代码进行分析。我在这里找到了各种具有背景页面和内容脚本的解决方案,但没有一个对我有帮助。这是我到目前为止所知道的:
manifest.json
{
"name": "Extension",
"version": "1.0",
"description": "Extension",
"browser_action": {
"default_icon": "bmarkred.ico",
"popup": "Test.html"
},
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["content.js"]
}
],
"background": {
"page": "backgroundPage.html"
},
"permissions": [
"cookies",
"tabs",
"http://*/*",
"https://*/*"
]
}
background.html
<html>
<head>
<script type="text/javascript">
try {
chrome.tabs.getSelected(null, function (tab) {
chrome.tabs.sendRequest(tab.id, {action: "getSource"}, function(source) {
alert(source);
});
});
}
catch (ex) {
alert(ex);
}
</script>
</head>
</html>
content.js
chrome.extension.onRequest.addListener(function(request, sender, callback) {
if (request.action == "getSource") {
callback(document.getElementsByTagName('html')[0].innerHTML);
}
});
警报总是未定义的警报。即使我在content.js文件中将回调函数更改为:
callback('hello');
结果仍然是一样的。我做错了什么?也许我做错了。我真正需要的是:当用户打开扩展弹出窗口(只有那时),我需要当前页面的HTML,以便我可以分析它。
发布于 2020-11-15 03:25:38
以下是我的解决方案:
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
this.pageSource = request.source;
var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
alert(title)
}
});
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
chrome.tabs.executeScript(
tabs[0].id,
{ code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
);
});
https://stackoverflow.com/questions/11684454
复制相似问题