12

I am trying to send a message from background.js to content.js using the following code:

Background

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

Content

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

The background message is sent when background.js receives a specific message from popup.js which occurs on a click event. So the user clicks a button in the popup and a message is sent to background and then to content.

I have a feeling my problem is something to do with the fact that when the button is clicked in the popup (which is a separate tab), the content script does not receive it because it is not the current active tab.

Please help me out.

ALR
  • 441
  • 2
  • 7
  • 19

1 Answers1

37

There are 2 sendMessage functions in Chrome API.

So, to send a message TO a content script, you need to use chrome.tabs. To send a message FROM a content script (or within the extension pages), you need to use chrome.runtime.

The event is chrome.runtime.onMessage in both cases.

See Messaging docs for more details.

Xan
  • 74,770
  • 16
  • 179
  • 206
  • 1
    This also helped me [here](http://stackoverflow.com/questions/27952019/chrome-runtime-onmessage-addlistener-not-registering-within-created-tab) when I thought my problems were coming from the other side – ljs.dev Jan 14 '15 at 23:16