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?
executeScript() Injects a script into a target context. The script is run at document_idle by default. Note: This method is available in Manifest V3 or higher in Chrome and Firefox 101. In Safari and Firefox 102+, this method is also available in Manifest V2.
You can use the chrome. scripting API to inject JavaScript and CSS into websites.
How to Create a Chrome Extension. First of all, we need to create an empty folder where we will add our HTML, CSS, and JavaScript files. Now, let's add a link to the Bootstrap CDN in the head tag. We will be using the Bootstrap framework here so that we don't have to write some extra CSS in this example.
This is my proposed solution:
function executeScripts(tabId, injectDetailsArray) { function createCallback(tabId, injectDetails, innerCallback) { return function () { chrome.tabs.executeScript(tabId, injectDetails, innerCallback); }; } var callback = null; for (var i = injectDetailsArray.length - 1; i >= 0; --i) callback = createCallback(tabId, injectDetailsArray[i], callback); if (callback !== null) callback(); // execute outermost function }
Subsequently, the sequence of InjectDetails
scripts can be specified as an array:
chrome.browserAction.onClicked.addListener(function (tab) { executeScripts(null, [ { file: "jquery.js" }, { file: "master.js" }, { file: "helper.js" }, { code: "transformPage();" } ]) });
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