I need to programmatically inject multiple script files (followed by a code snippet) into the current page from my Google Chrome extension. The chrome.tabs.executeScript met
This is mostly an updated answer (on the other answer) :P
const executeScripts = (tabId, scripts, finalCallback) => {
try {
if (scripts.length && scripts.length > 0) {
const execute = (index = 0) => {
chrome.tabs.executeScript(tabId, scripts[index], () => {
const newIndex = index + 1;
if (scripts[newIndex]) {
execute(newIndex);
} else {
finalCallback();
}
});
}
execute();
} else {
throw new Error('scripts(array) undefined or empty');
}
} catch (err) {
console.log(err);
}
}
executeScripts(
null,
[
{ file: "jquery.js" },
{ file: "master.js" },
{ file: "helper.js" },
{ code: "transformPage();" }
],
() => {
// Do whatever you want to do, after the last script is executed.
}
)
Or return a promise.
const executeScripts = (tabId, scripts) => {
return new Promise((resolve, reject) => {
try {
if (scripts.length && scripts.length > 0) {
const execute = (index = 0) => {
chrome.tabs.executeScript(tabId, scripts[index], () => {
const newIndex = index + 1;
if (scripts[newIndex]) {
execute(newIndex);
} else {
resolve();
}
});
}
execute();
} else {
throw new Error('scripts(array) undefined or empty');
}
} catch (err) {
reject(err);
}
});
};
executeScripts(
null,
[
{ file: "jquery.js" },
{ file: "master.js" },
{ file: "helper.js" },
{ code: "transformPage();" }
]
).then(() => {
// Do whatever you want to do, after the last script is executed.
})