如何获取javascript中的chrome选项卡源代码
我尝试开发一个chrome扩展,我需要能够获得当前选项卡的源代码,因此我遵循chrome示例,我有三个文件: manifest.json:如何获取javascript中的chrome选项卡源代码,javascript,google-chrome,google-chrome-extension,tabs,Javascript,Google Chrome,Google Chrome Extension,Tabs,我尝试开发一个chrome扩展,我需要能够获得当前选项卡的源代码,因此我遵循chrome示例,我有三个文件: manifest.json: { "manifest_version": 2, "name": "Source code getter", "description": "This extension is a test to get current tab source code", "version": "0.1", "browser_acti
{
"manifest_version": 2,
"name": "Source code getter",
"description": "This extension is a test to get current tab source code",
"version": "0.1",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs"
]
}
popup.html:
<!doctype html>
<html>
<head>
<title>Get source popup</title>
<style>
body {
min-width: 357px;
min-height: 357px;
overflow-x: hidden;
}
</style>
<script src="popup.js"></script>
</head>
<body>
</body>
</html>
我通过在网上搜索来构建popup.js,我必须承认我真的不知道sendMessage是如何工作的,但我认为第二个参数ask the source code必须在function response的参数中返回,但它没有,以下是js日志:
430 popup.js:4
> Error in event handler for (unknown): Cannot read property 'html' of undefined
> Stack trace: TypeError: Cannot read property 'html' of undefined
> at chrome-extension://boefdmhphdcngpckofecmjnihbgphmch/popup.js:7:35
> at disconnectListener (extensions::messaging:338:9)
> at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
> at EventImpl.dispatchToListener (extensions::event_bindings:397:22)
> at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
> at Event.publicClass.(anonymous function) [as dispatchToListener] (extensions::utils:93:26)
> at EventImpl.dispatch_ (extensions::event_bindings:379:35)
> at EventImpl.dispatch (extensions::event_bindings:403:17)
> at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
> at Event.publicClass.(anonymous function) [as dispatch] (extensions::utils:93:26)
所以我得到了正确的标签,但是我没有得到正确的响应表单sendMessage函数,有人可以解释为什么?谢谢。从您的清单判断,您没有听到您发送的消息 清单中未定义内容脚本,因此页面中未加载任何内容;弹出代码中没有executeScript调用,因此不会加载任何内容 因此,不需要处理您的消息,并且调用回调时会出现一个错误集。您的消息{action:getHtml}并没有神奇的意义;您需要在页面的一侧有一个脚本来接收它并形成响应 您需要的是一个将为chrome.runtime.onMessage添加侦听器的应用程序,它将处理您的请求。我们称之为content.js。然后你可以这样做:
chrome.tabs.executeScript({code: "content.js"}, function() {
if(chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
return;
}
chrome.tabs.sendMessage(tab.id, {action: "getHtml"}, function(response) {
/* process response */
});
});
相应content.js的代码超出了本问题的范围。也请看一下,它很好地介绍了内容脚本的工作原理
chrome.tabs.executeScript({code: "content.js"}, function() {
if(chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
return;
}
chrome.tabs.sendMessage(tab.id, {action: "getHtml"}, function(response) {
/* process response */
});
});