Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension: Send message from background script to *all* tabs

Is there a way to have the background script inform all currently open tabs (i.e. their content scripts) that an event took place.

Something like the following basically

chrome.tabs.sendMessage("*", {foo: "bar"}) 

I suspect I could maintain a list of open tabs on the background script, if that's possible, and use that. But is there a simpler way?

like image 709
Himanshu P Avatar asked Apr 16 '13 20:04

Himanshu P


People also ask

How do you send a message from content script?

If you only need to send a single message to another part of your extension (and optionally get a response back), you should use the simplified runtime. sendMessage or tabs. sendMessage. This lets you send a one-time JSON-serializable message from a content script to extension, or vice versa, respectively.

How do I make Chrome ask before closing all tabs?

Select "Settings" from the drop-down menu. Click the "Extensions" tab, locate "Chrome Toolbox by Google," and then click the "Options" link under the description of the extension. Check the box next to "Confirm Before Closing Multiple Tabs" in the "Tabs" section to automatically update your browser's settings.


2 Answers

The wildcard is not supported. The only way to reach all tabs is to query all existing tabs, and dispatch the message using chrome.tabs.sendMessage.

chrome.tabs.query({}, function(tabs) {     var message = {foo: bar};     for (var i=0; i<tabs.length; ++i) {         chrome.tabs.sendMessage(tabs[i].id, message);     } }); 
like image 97
Rob W Avatar answered Sep 17 '22 16:09

Rob W


Taken from Rob W's example. This is probably a little better:

chrome.tabs.query({}, (tabs) => tabs.forEach( tab => chrome.tabs.sendMessage(tab.id, message) ) ); 
like image 32
Steve S Avatar answered Sep 16 '22 16:09

Steve S