Chrome Extension - Find all open tabs and execute script on all

给你一囗甜甜゛ 提交于 2019-12-06 10:42:32

问题


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

回答1:


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



回答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.




回答3:


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


来源:https://stackoverflow.com/questions/21917168/chrome-extension-find-all-open-tabs-and-execute-script-on-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!