2013-02-12 56 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