Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting multiple scripts through executeScript in Google Chrome

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?

like image 359
Douglas Avatar asked Feb 03 '14 18:02

Douglas


People also ask

What is Chrome scripting executeScript?

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.

Can you write scripts in Chrome?

You can use the chrome. scripting API to inject JavaScript and CSS into websites.

How do you create a Chrome extension?

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.


1 Answers

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();" }     ]) }); 
like image 186
Douglas Avatar answered Sep 21 '22 05:09

Douglas