javascript Chrome 扩展中的多个 JS 文件 - 如何加载它们?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18651620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple JS files in Chrome Extension - how to load them?
提问by Tomasz Banasiak
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).
我写了一个 Chrome 扩展。我的 background.js 文件很大,所以我想把它拆分成更小的部分,并在需要时加载指定的方法(某种延迟加载)。
I've done this with Firefox:
我已经用 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.
在基于 Webkit 的浏览器中是否有可能以类似的方式执行此操作?我找到了有关如何将多个 JS 文件注入匹配页面(使用manifest.json
)的解决方案,但找不到仅用于扩展名的包含 JS 文件的方法。
采纳答案by Tomasz Banasiak
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
找到了可能的解决方案。有一个 RequireJS main 方法 require 的简单实现,它使用 JavaScript 回调跟踪来查找加载主扩展文件的事件,并将其与扩展上下文绑定执行。 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
- 错误报告在“第 1 行,第 1 列”中报告,因为此解决方案将代码直接注入到
func.call
- 调试非常困难 - 加载的 JS 文件没有出现在控制台/chromebug 中
- 如果当前选项卡使用 HTTPS,Chrome 将禁止评估脚本,尤其是来自本地上下文 (
file:///
) 的脚本,因此它有时无法按预期工作
回答by Omn
You can also do this the extremely easy way that is described here: https://developer.chrome.com/extensions/background_pages#manifest
您也可以使用此处描述的极其简单的方法执行此操作: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.
您不会进行延迟加载,但它确实允许您将代码分成多个文件并指定它们加载到后台页面的顺序。
回答by rsanchez
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:
如果您想在后台页面的上下文中加载 javascript 文件并希望避免使用eval
,您只需script
向后台页面的 DOM添加一个标签即可。例如,如果您的文件存在于lib
您的扩展文件夹中,这将起作用:
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);
}
回答by mdenton8
You could attempt to use web workers, perhaps. In your background.js, include:
也许您可以尝试使用网络工作者。在您的 background.js 中,包括:
var worker = new Worker('new-script.js');
Web workers can spawn new workers, and even have an importScript("new-script.js") method.
Web worker 可以产生新的 worker,甚至有一个 importScript("new-script.js") 方法。
Web workers can tend to be very limited, however. Check herefor a great article on Web workers.
然而,网络工作者往往非常有限。检查这里的基于Web的工人一个伟大的文章。
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
:
但是,我不知道它们是否会起作用。另一种选择是使用 XMLHTTPRequest (AJAX) 来动态检索脚本并对其进行评估。然而,通过非 HTTPS 连接,这可能会由于中间人攻击而被阻止。或者,您可以通过将以下内容添加到manifest.json
以下内容来强制 Chrome 从非加密连接(但不要这样做)评估脚本:
"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 Extensionfor a more in-depth discussion of the AJAX method.
有关AJAX 方法的更深入讨论,请参阅在后台页面中加载远程网页:Chrome 扩展程序。
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
},
...
}
回答by Ryan Walker
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 扩展程序图标时先加载一些文件。就我而言,我希望我的 util 文件在其他人使用它们之前:
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"});
});