我正在编写Chrome扩展,我试图在背景页面和内容页面之间发送消息。无法在背景页面和内容页面之间建立连接
问题是连接永远不会建立。我甚至从谷歌文档复制代码,但无济于事。
这里是我的清单页面
{
"name": "x",
"description": "x",
"version": "0.1",
"permissions": ["contextMenus", "tabs", "notifications"],
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"js": ["jquery.js", "content_script.js"]
}
],
"background": {
"scripts": ["sample.js"]
},
"manifest_version": 2
}
我的背景页面
function genericOnClick(info, tab)
{
//copy pasted from google tutorials. My own code also didn't work
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
}
// Create a parent item and two children.
var parent1 = chrome.contextMenus.create({"title": "Rank Trigger", "contexts":["all"]});
var child1 = chrome.contextMenus.create
(
{"title": "Rank 1", "contexts":["all"], "parentId": parent1, "onclick": genericOnClick}
);
var child2 = chrome.contextMenus.create
(
{"title": "Rank 2", "contexts":["all"], "parentId": parent1, "onclick": genericOnClick}
);
var child2 = chrome.contextMenus.create
(
{"title": "Rank 3", "contexts":["all"], "parentId": parent1, "onclick": genericOnClick}
);
内容脚本:
//copied from google tutorials
chrome.extension.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"});
});
有什么想法吗?也许因为事件是从上下文菜单触发的,但我不太确定。我是JS和chrome扩展编程的新手。
感谢
'genericOnClick(e)'传递事件对象为'e',正确吗?所以你需要'e.target',还是我误会了? – 2013-02-12 16:06:17
我在发布代码后编辑代码时编写的错别字......两者都是我的代码中的“事件”。 :) – r3x 2013-02-12 17:17:15
你应该显示你正在使用的代码来设置处理程序 – 2013-02-12 21:38:20