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"});
});
}
});
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"});
}
});
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With