THE PROCESS:
I created a Google Chrome extension and I placed a button in the options page of this extension. When this button is clicked, it is supposed to execute the code written in options.js file (referring to the function loopTabsAndWriteToConsole), loop through all the open tabs and send a dynamic variable (the iteration number) to the content script. The content script then writes the dynamic variable to the console log of the respective tab, that is being currently accessed by the script.
THE ISSUE:
When the button in the options page is clicked, it does NOT write the expected values to console in each of the tabs that are open.
How can the code be fixed so that when the button is clicked, the script options.js and the function loopTabsAndWriteToConsole are executed, and the dynamic variable/iteration count is written to the console with respect to the tab executed? That is, the dynamic variable/iteration count should be written to the console of the tab that is being accessed by the script.
For example, this is what I expect when I have 5 tabs in the browser and I click the button:
1st Tab Console log: 0
2nd Tab Console log: 1
3rd Tab Console log: 2
4th Tab Console log: 3
5th Tab Console log: 4
In the above code, the values: 0, 1, 2, 3, 4 refer to the iteration number of the for loop (i.e. the tabs that are currently open in my browser window).
Following are my HTML and JS codes:
HTML:
<button id="btnWrite" type="button" class="btn btn-primary btn-block btn-lg">ALL TABS: Write to Console</button>
options.js:
document.getElementById('btnWrite').addEventListener('click', loopTabsAndWriteToConsole);
function loopTabsAndWriteToConsole() {
chrome.tabs.query({}, function (tabs) {
for (var i = 0; i < tabs.length; i++) {
chrome.tabs.executeScript(tabs[i].id, {code: "var config = '" + (i) + "';"}, function () {
chrome.tabs.executeScript(tabs[i].id, {file: "scripts/my_script.js"});
});
}
});
}
my_script.js:
function writeToConsole() {
console.warn(config);
}
writeToConsole();
UPDATE 1:
The following code gets executed but I am unable to pass the dynamic variable/iteration count to log it to console:
chrome.tabs.query( {} ,function (tabs) {
for (var i = 0; i < tabs.length; i++) {
chrome.tabs.executeScript(tabs[i].id, {file: "scripts/my_script.js"});
}
});
SOLUTION:
I figured out a solution for the issue. The following is the revised function that I am using.
function loopTabsAndWriteToConsole() {
chrome.tabs.query({}, function (tabs) {
for (var i = 0; i < tabs.length; i++) {
(function (i) {
chrome.tabs.executeScript(tabs[i].id, {code: "var config = '" + (i) + "';"}, function () {
chrome.tabs.executeScript(tabs[i].id, {file: "scripts/my_script.js"});
});
})(i);
}
});
}