我正在开发一个非常简单的浏览器扩展,但无法将消息传递给工作: 我可以发送消息,但是响应永远不会发送!
我的代码: 它主要只是来自browserActions教程,contentscripts教程(manifest)和消息传递api定义的副本。
的manifest.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://*/*"]
}],
}
background.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>
答案 0 :(得分:0)
由于每次加载弹出窗口时都会发送从弹出窗口到内容脚本的消息,因此请务必重新加载页面以确保加载内容脚本。否则,您最终可能会收到以下错误:
Could not establish connection. Receiving end does not exist.
那就是说,我试过你提供的东西,它按原样运作。由于您的输出位于popup.js中,因此响应位于弹出窗口的控制台输出中。您可以通过右键单击浏览器操作图标并选择“检查弹出窗口”来查看它。