问题
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