我是 chrome 扩展的新手,入门时遇到了一些麻烦。
首先,我的总体目标是能够单击弹出窗口中的按钮并在 DOM 中进行一些更改。如果我理解正确的话,这样做的方法是加载一个内容脚本并向这个内容脚本发送一条消息。这是我查看 Chrome 开发人员页面所得到的,但我在控制台日志中看不到任何内容:
清单.json
{
"manifest_version": 2,
"name": "Test",
"version": "1.0",
"permissions": [
"tabs", "http://*/*"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["content.js"]
}
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}
popup.html
<html>
<body>
<script src="popup.js"></script>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', function () {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
});
内容.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
很多代码直接来自文档,所以我不知道我做错了什么。