2014-11-05 76 views
3

我尝试使用下面的代码从background.js将消息发送到content.jsChrome扩展:从background.js消息content.js

背景

chrome.runtime.sendMessage({'method': 'test'}); 

内容

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){ 
    if(message.method == 'test') 
    console.log('Got message'); 
}); 

后台消息发送时background.js从发生在点击事件上的popup.js收到特定消息。因此,用户点击弹出窗口中的按钮,并将消息发送到后台然后发送到内容。

我有一种感觉,我的问题是这样的事实,即当在弹出窗口(这是一个单独的选项卡)中单击该按钮时,内容脚本不会收到它,因为它不是当前活动选项卡。

请帮我一把。

回答

9

在Chrome API中有2 sendMessage函数。

所以,要发送消息到内容脚本,您需要使用chrome.tabs。要从内容脚本(或扩展页面内)发送消息,您需要使用chrome.runtime

两种情况下的事件都是chrome.runtime.onMessage

有关更多详细信息,请参阅Messaging docs

+0

这很有道理!感谢您的帮助。 – ALR 2014-11-06 08:36:09

+0

当我认为我的问题来自对方时,这也帮助了我[这里](http://stackoverflow.com/questions/27952019/chrome-runtime-onmessage-addlistener-not-registering-within-created-tab) – 2015-01-14 23:16:45

相关问题