Multiple JS files in Chrome Extension - how to load them?

人走茶凉 提交于 2020-01-22 05:40:17

问题


I've wrote a Chrome Extension. My background.js file is quite large, so I want to split it to smaller parts and load specified methods when required (some kind of lazy-loading).

I've done this with Firefox:

// ( call for load specified lib )
var libPath = redExt.basePath + 'content/redExt/lib/' + redExt.browser + '/' + libName + '.js';
var service = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
service.loadSubScript("chrome://" + libPath);
// ( executing loaded file )

Is there any possiblity to do it similar way in Webkit-based browsers? I've found solutions for how to inject multiple JS files into matching pages (using manifest.json) but cannot find way to include JS file just for extension.


回答1:


You can also do this the extremely easy way that is described here: https://developer.chrome.com/extensions/background_pages#manifest

{
  "name": "My extension",
  ...
  "background": {
    "scripts": [
      "lib/fileone.js",
      "lib/filetwo.js",
      "background.js"
    ]
  },
  ...
}

You won't be doing lazy loading, but it does allow you to break your code up into multiple files and specify the order in which they are loaded onto the background page.




回答2:


If you want to load a javascript file in the context of your background page and want to avoid using eval, you can just add a script tag to your background page's DOM. For instance, this works if your files are present in the lib folder of your extension:

function loadScript(scriptName, callback) {
    var scriptEl = document.createElement('script');
    scriptEl.src = chrome.extension.getURL('lib/' + scriptName + '.js');
    scriptEl.addEventListener('load', callback, false);
    document.head.appendChild(scriptEl);
}



回答3:


You could attempt to use web workers, perhaps. In your background.js, include:

var worker = new Worker('new-script.js');

Web workers can spawn new workers, and even have an importScript("new-script.js") method.

Web workers can tend to be very limited, however. Check here for a great article on Web workers.

I don't know if they would work, however. The other option is using XMLHTTPRequest (AJAX) to dynamically retrieve the script, and eval it. Over a non-HTTPS connection however, this is probably blocked due to man-in-the-middle attacks. Alternatively, you can force Chrome to eval script from a non-encrypted connection (BUT DON'T DO IT) by adding this to manifest.json:

"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"permissions": ["http://badpractic.es/insecure.js"]

See Load remote webpage in background page: Chrome Extension for a more in-depth discussion of the AJAX method.

So your options seem to be limited.

This of course loads them all at once:

{
  "name": "My extension",
  ...
  "background": {
    "scripts": ["background.js","background2.js","background3.js"] //and so on
  },
  ...
}



回答4:


Found possible solution. Theres a simple implementation of RequireJS main method require which uses JavaScript callback trace to find event for loading main extension file and binds executes it with extension context. https://github.com/salsita/browser-require/blob/master/require.js

It seems to work, but this solution has a few cons:

  • bug reports are reported in "line 1, column 1" because this solution injects code directly to func.call - debugging is very hard
  • Loaded JS files does not appear in console / chromebug
  • If current tab uses HTTPS Chrome will disallow evaling scripts, especially this from local context (file:///), so it sometimes just dont work as expected



回答5:


What I've done isn't lazy loading but I load some files before the others when my chrome extension icon is clicked. In my case, I wanted my util files before the others that utilize them:

chrome.browserAction.onClicked.addListener(function() {
  chrome.tabs.executeScript(null, {file: "src/utils/utilFunction1.js"});
  chrome.tabs.executeScript(null, {file: "src/utils/utilFunction2.js"});
  chrome.tabs.executeScript(null, {file: "src/main.js"});
  chrome.tabs.executeScript(null, {file: "src/otherFeature.js"});
});


来源:https://stackoverflow.com/questions/18651620/multiple-js-files-in-chrome-extension-how-to-load-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!