Keven Wang
Keven Wang

Reputation: 1268

chrome broadcast message to content scripts

Is there a way to broadcast a chrome message to all content scripts of a chrome extension?

chrome.runtime.sendMessage() takes a tabId as an input. However if there are multiple tabs running with the content script, how could one broadcast to all the tabs?

Upvotes: 4

Views: 2278

Answers (1)

Xan
Xan

Reputation: 77502

I assume you meant chrome.tabs.sendMessage having the tab ID argument.

There are 2 sendMessage functions in Chrome API:

That would be the background page, the popup (if open), the options page (if open) and any tabs to extension pages you opened yourself.

  • chrome.tabs.sendMessage will broadcast to all content scripts of your extension running in the tab provided (soon with a possiblity to filter by frame), or the current active tab if the ID is not provided.

There is, unfortunately, no function to broadcast to all content scripts. So, you have two possible approaches:

1 - Carpet bombing

Just broadcast to all tabs one by one!

chrome.tabs.query({}, function(tabs) {
  tabs.forEach(function(tab) {
    chrome.tabs.sendMessage(tab.id, message);
  });
});

If you want to narrow it down by match pattern, you can:

// Even accepts arrays of patterns!
chrome.tabs.query({url: "*://*.example.com/*"}, function(tabs) {
  tabs.forEach(function(tab) {
    chrome.tabs.sendMessage(tab.id, message);
  });
});

2 - Tab/connection tracking

You can be more proactive and track the tabs that are ready to receive your messages. It can be tedious, however, to maintain that list.

In practice, you can instead make your content scripts open port connections to your background page, and then use the list of open ports to send a command to them. The downside being that you can't use an event page for this, as it needs to keep connections open.

Upvotes: 6

Related Questions