Search code examples
google-chrome-extension

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?


Solution

  • 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);
        }
    });