我正在开发一个非常简单的浏览器扩展程序,但无法让消息传递工作:我可以发送消息,但永远不会传递响应!
我的代码:它主要是 browserActions 教程、contentscripts 教程(清单)和消息传递 api 定义的副本。
清单.json:
{
"manifest_version":2,
"name": "FUN SCRIPT",
"version": "1",
"description": "THIS IS SOME FUN SCRIPT",
"browser_action": {
"name": "Fun",
"icons": ["icon.png"],
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [ {
"js": [ "jquery.js", "background.js" ],
"matches": [ "http://*/*", "https://*/*"]
}],
}
背景.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"});
});
popup.js
document.addEventListener('DOMContentLoaded', function () {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
});
popup.html
<!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>
<style>
body {
min-width: 357px;
overflow-x: hidden;
}
img {
margin: 5px;
border: 2px solid black;
vertical-align: middle;
width: 75px;
height: 75px;
}
</style>
<script src="popup.js"></script>
</head>
<body>
</body>
</html>