2013-02-12 91 views
-1

我正在編寫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擴展編程的新手。

感謝

+0

'genericOnClick(e)'傳遞事件對象爲'e',正確嗎?所以你需要'e.target',還是我誤會了? – 2013-02-12 16:06:17

+0

我在發佈代碼後編輯代碼時編寫的錯別字......兩者都是我的代碼中的「事件」。 :) – r3x 2013-02-12 17:17:15

+0

你應該顯示你正在使用的代碼來設置處理程序 – 2013-02-12 21:38:20

回答

0

原來我的代碼按預期工作,並確實發送了每個onClick消息。問題在於我在沒有注入contentScript的錯誤頁面上測試它。

我的部分愚蠢的錯誤...感謝所有幫助

1

建立一個onclick處理程序的元素,然後使用event.currentTarget.outerHTML來獲取點擊的元素的HTML。

+0

得到了以下錯誤,我需要「#include」什麼? 錯誤爲「contextMenus」事件處理程序:無法讀取未定義類型錯誤的特性「outerHTML」:在genericOnClick無法讀取的不確定 財產「outerHTML」(鉻擴展://inhjfhckdfpegapembanojbhadkkkdme/sample.js:5:30) 在contextMenus:42:17在 chrome.Event.dispatchToListener(event_bindings:387:21) 在chrome.Event.dispatch_(event_bindings:373:27) 在dispatchArgs(event_bindings:249:22) 在Object.chromeHidden。 Event.dispatchEvent(event_bindings:257:7) – r3x 2013-02-12 17:20:13

+0

這意味着你沒有正確引用元素。當您觸發onclick函數時,請將傳入該函數的事件對象取出並查看它是否具有已定義的currentTarget屬性。該currentTarget屬性應該是對你想要的元素的引用... – kinsho 2013-02-12 20:13:38

+0

我認爲問題是從後臺頁面發送消息到內容頁面。我再次編輯了這個問題,以減少本地化。 – r3x 2013-02-13 15:42:37