我一直在谷歌搜索广泛试图解决这个问题,但似乎无法找到解决方案。我正在尝试执行在Chrome扩展程序中设置侦听器和发件人的简单任务。
我的清单
{
"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非常不错,我不清楚为什么这会表现得很奇怪。任何帮助都将非常感激!
答案 0 :(得分:3)
此代码存在多个问题,所以让我分解一下。
从我看到你试图从你的内容脚本向你的弹出窗口发送一条消息,并且有一个背景页面没有做任何事情。
问题#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));
});
});
答案 1 :(得分:0)
我在后台页面遇到了类似的问题,我的解决方案是确保标签在尝试发送消息之前已完成加载。
如果选项卡尚未完全加载,则内容脚本将不会启动,也不会等待消息。
以下是一些代码:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete') {
// can send message to this tab now as it has finished loading
}
}
因此,如果您要向活动标签发送消息,可以确保先完成加载。