Injecting multiple scripts through executeScript in Google Chrome

后端 未结 5 2162
渐次进展
渐次进展 2020-12-04 22:25

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

5条回答
  •  温柔的废话
    2020-12-04 23:15

    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.
    })
    
    

提交回复
热议问题