Google Chrome Extensions: How to include jQuery in programmatically injected content script?

后端 未结 5 1193
轮回少年
轮回少年 2020-11-28 22:33

I\'m injecting my content script from the background page when the user clicks the browser action button, like so:

chrome.browserA         


        
5条回答
  •  不知归路
    2020-11-28 23:13

    Since I've much scripts with many dependencies , I use a function concatenateInjection that takes three parameters:

    //id: the tab id to pass to executeScript
    //ar: an array containing scripts to load ( index order corresponds to execution order)
    //scrpt (opzional): the last script to execute (if not provided, than the last script is the last insert in previous array)
    
    function concatenateInjections(id, ar, scrpt){
      var i = ar.length;
      var idx = 0;
    
      function inject(idx){
        idx++;
        if(idx <= i){
          var f = ar[idx-1];
          chrome.tabs.executeScript(id, { file: f }, function() {
              inject(idx);
          });
        }else{
          if(typeof scrpt === 'undefined') return;
          chrome.tabs.executeScript(id, { file: scrpt });
        }
      }
      inject(idx);
    }
    

    and usage example:

    // id is tab id
    
    // sources: first execute jquery, than default.js and anime.js in the end
    var def = [
      "lib/jquery-1.11.3.min.js", 
      "lib/default.js", 
      "injection/anime.js"
    ];
    
    // run concatenate injections
    concatenateInjections(id, def);
    

    Think that's could be useful.

    UPDATE

    Version with concat and closure (more aesthetic):

    function concatenateInjections(id, ar, scrpt){
    
      if( typeof scrpt !== 'undefined' ) ar = ar.concat([scrpt]);
    
      var i = ar.length;
      var idx = 0 ;
    
      (function (){
        var that = arguments.callee;
        idx++;
        if(idx <= i){
          var f = ar[idx-1];
          chrome.tabs.executeScript(id, { file: f }, function(){ that(idx);} );
        }
      })();
    
    }
    

提交回复
热议问题