我尝试开发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_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
document.addEventListener('DOMContentLoaded', function() {
chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
var tab = tabs[0];
console.debug(tab.id);
var source = document.createElement("div");
chrome.tabs.sendMessage(tab.id, {action: "getHtml"}, function(response) {
console.debug(response.html);
if (response.html) {
source.textContent = response.html;
} else {
source.textContent = 'I did not get the source code.';
}
});
document.body.appendChild(source);
});
});
我通过在网上搜索来构建popup.js我必须承认我并不真正知道sendMessage是如何工作的,也是the doc但我认为第二个参数询问源代码是什么必须在函数响应的参数中返回,但它不是,这里是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功能,有人可以解释我为什么?感谢。
答案 0 :(得分:0)
根据你的证词判断,你没有听取sendMessage
的任何内容。
清单中没有定义内容脚本,因此页面中没有任何内容;弹出代码中没有executeScript
个调用,因此没有任何内容从那里加载。
因此,没有处理您的消息,并且使用错误集调用回调。您的消息{action: "getHtml"}
并不神奇地表达任何意义;您需要页面旁边的脚本才能接收并形成回复。
您需要的是content script,它将为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
的代码超出了本问题的范围。看看Architecture Overview,它也很好地介绍了内容脚本的工作原理。