Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension: message from background.js to content.js

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.

like image 305
ALR Avatar asked Nov 05 '14 20:11

ALR


People also ask

What does background js do in Chrome extension?

The background script is a script running in the background to handle majority of chrome events that content scripts cannot. Content scripts are purely the content of the each page.

Can Chrome run background extensions?

Run In Background. Run Chrome in the background continuously. This extension simply keeps Chrome running in the background, so that push notifications can be received while the browser is closed.


1 Answers

There are 2 sendMessage functions in Chrome API.

  • chrome.runtime.sendMessage sends a message to all open extension pages (i.e. background, popup, etc.)
  • chrome.tabs.sendMessage sends a message to all content scripts from the extension in a given tab (possibly filtered by frame ID)

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.

like image 94
Xan Avatar answered Sep 29 '22 11:09

Xan