我一直在谷歌上广泛搜索,试图解决这个问题,但似乎找不到解决方案。我正在尝试在我的 Chrome 扩展程序中完成设置监听器和发送器的简单任务。
我的 list
{
"manifest_version": 2,
"name": "my app",
"description": "text",
"version": "0.1",
"background":{
"scripts":["background.js"]
},
"content_scripts": [
{
// http://developer.chrome.com/extensions/match_patterns.html
"matches": ["http://myurl.com/*"],
"js": ["jquery-1.9.1.min.js", "myapp.js"],
"all_frames": true
}
],
"browser_action": {
"default_icon": "/icons/icon-mini.png",
"default_popup": "popup.html"
}
}
在我的后台JS
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
在我的popup.js中(用coffeescript渲染的,语法怪怪的请见谅)
(function() {
$(function() {});
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (console.log(sender.tab)) {
"from a content script:" + sender.tab.url;
} else {
"from the extension";
}
if (request.greeting === "hello") {
return sendResponse({
farewell: "goodbye"
});
}
});
}).call(this);
在我的 myapp.js 中
chrome.extension.sendMessage({
greeting: "hello"
}, function(response) {
return console.log(response.farewell);
});
我关注了the tutorial .不知道为什么这不起作用。我对 JS 相当满意,非常不清楚为什么这会表现得很奇怪。任何帮助将不胜感激!
最佳答案
这段代码有不止一个问题,所以让我分解一下。
据我所知,您正在尝试从您的内容脚本向您的弹出窗口发送一条消息,但背景页面没有执行任何操作。
问题 #1
popup.js中的代码,除了奇葩之外,并不是后台页面。它仅在 popup
打开时运行,因此它将无法监听消息。
问题 #2
后台页面中的代码使用已弃用的 getSelected
方法向内容脚本发送消息。内容脚本没有监听器。
这两件事的结果是这样的:
Background page -> content script (no listener)
Content Script -> extension pages (no listener)
我建议让您的背景页面成为您的交流中心。如果您需要在弹出窗口和内容脚本之间进行通信,请使用 popup -> content script
并使用 sendResponse()
进行回复。
编辑:这是您想要的消息传递示例。只需替换为您的变量即可。
内容脚本
...
//get all of your info ready here
chrome.extension.onMessage.addListener(function(message,sender,sendResponse){
//this will fire when asked for info by the popup
sendResponse(arrayWithAllTheInfoInIt);
});
弹窗
...
chrome.tabs.query({'active': true,'currentWindow':true},function(tab){
//Be aware 'tab' is an array of tabs even though it only has 1 tab in it
chrome.tabs.sendMessage(tab[0].id,"stuff", function(response){
//response will be the arrayWithAllTheInfoInIt that we sent back
//you can do whatever you want with it here
//I will just output it in console
console.log(JSON.stringify(response));
});
});
关于javascript - 端口错误 : Could not establish connection. 接收端不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15366646/