【发布时间】:2013-01-27 23:56:26
【问题描述】:
我正在编写 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,还是我弄错了? -
我在这里发布代码后编辑代码时写的一个错字......两者都是我代码中的“事件”。 :)
-
你应该显示你用来设置处理程序的代码
-
按要求编辑了代码
标签: javascript html events dom google-chrome-extension