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
method allows for a single InjectDetails
object (representing a script file or code snippet), as well as a callback function to be executed after the script. Current answers propose nesting executeScript
calls:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, { file: "jquery.js" }, function() {
chrome.tabs.executeScript(null, { file: "master.js" }, function() {
chrome.tabs.executeScript(null, { file: "helper.js" }, function() {
chrome.tabs.executeScript(null, { code: "transformPage();" })
})
})
})
});
However, the callback nesting gets unwieldy. Is there a way of abstracting this?
This is my proposed solution:
Subsequently, the sequence of
InjectDetails
scripts can be specified as an array:From Chrome v32, it supports Promise. We should use it for making code clean.
Here is an example:
ScriptExecution
source:If you would like to use ES5, you can use online compiler to compile above codes to ES5.
Fork me on GitHub: chrome-script-execution
Given your answer, I expected synchronously injecting the scripts to cause problems (namely, I thought that the scripts might be loaded in the wrong order), but it works well for me.
This assumes you only want one callback at the end and don't need the results of each executed script.