4

Trying to modify my code for when the extension button is clicked, it will execute on all open tabs instead of only the active one.

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null, { file: "jquery-2.1.0.min.js" }, function() {
    chrome.tabs.executeScript(null, {file: "change.js"});
  });
});

manifest.json

{
  "manifest_version": 2,    
  "name": "GSHOP",
  "version": "2",
  "description": "I do Stuff",
  "background": {
    "persistent": false,
    "scripts": ["jquery-2.1.0.min.js", "background.js"]
   },
  "browser_action": {
    "name": "Manipulate DOM",
    "icons": ["icon.png"],
    "default_icon": "icon.png"
  },
  "permissions": [
    "activeTab",
    "tabs",
    "http://*/*", "https://*/*"
    ]
}

I believe I have the logic down I just can't figure how to do it. I believe I need to find how many tabs are open tabs.length? and iterate over them, but I just cannot get it to work.

Doesn't Work

chrome.browserAction.onClicked.addListener(function(tabs) {
            for (var i = 0; i < tabs.length; i++) {

            chrome.tabs.executeScript(tabs[i].id, {file: "jquery-2.1.0.min.js" },    function() {
            chrome.tabs.executeScript(tabs[i].id, {file: "change.js"});
            });
            }
        });
ToddN
  • 2,901
  • 14
  • 56
  • 96

3 Answers3

4

Try like this:

chrome.browserAction.onClicked.addListener(function (tab) {
  chrome.tabs.query( {} ,function (tabs) { // The Query {} was missing here
    for (var i = 0; i < tabs.length; i++) {
      chrome.tabs.executeScript(tabs[i].id, {file: "jquery-2.1.0.min.js"});
      chrome.tabs.executeScript(tabs[i].id, {file: "change.js"});
    }
  });
});
Cagy79
  • 1,610
  • 1
  • 19
  • 25
fulme
  • 312
  • 1
  • 4
2

chrome.browserAction.onClicked callbacks take a single tab object for the current tab. Not a list of all tabs. Inside the onClicked callback you will have to run chrome.tabs.query and loop through the tabs in the query callback.

abraham
  • 46,583
  • 10
  • 100
  • 152
2

Try this one. Hope this one helps.

chrome.browserAction.onClicked.addListener(function(tab) {
    executeScriptsInExistingTabs();
});

function executeScriptsInExistingTabs(){
    chrome.windows.getAll(null, function(wins) {
      for (var j = 0; j < wins.length; ++j) {
        chrome.tabs.getAllInWindow(wins[j].id, function(tabs) {
          for (var i = 0; i < tabs.length; ++i) {
            if (tabs[i].url.indexOf("chrome://") != 0) {
              chrome.tabs.executeScript(tabs[i].id, { file: 'js/change.js' });
            }
          }
        });
      }
    });
}
Mnick
  • 233
  • 3
  • 15