我正在編寫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