0

在 Mozilla 的 JavaScript 环境中,可以使用mozIJSSubScriptLoader 接口的 loadSubScript() 方法从 URL 加载其他脚本。

可以指定一个对象用作正在执行的脚本的范围对象。但是,正如Stackoverflow 答案中所解释的,“仍将在外部范围内创建未声明的变量,并且将在外部范围内搜索无法在下标范围内解析的变量。”

此答案建议使用Components.utils.Sandbox作为替代方案。

但是,这种机制显然会启用安全限制。对于Mozilla 错误 876089,我尝试简单地将常规 JS 对象替换为沙箱。然后,加载的脚本将不再使用 Components.utils,它以“Cu”的形式放置在范围对象中:

例外:调用方法 UnnamedClass.import 的权限被拒绝

现在的问题是:在 Mozilla 环境中,我如何才能最好地加载脚本,以防止通过调用者的全局对象泄漏符号,但仍然允许它使用明确放置在范围对象中的所有符号而不施加任何安全限制?

4

1 回答 1

1

事实上,使用沙盒是正确的方法。可以通过使用特殊主体作为范围对象而不是普通的 JavaScript 对象来管理安全设置。

通过使用system principal,所有安全检查都被禁用。

然后代码如下所示:

Components.utils.import("resource://gre/modules/Services.jsm");
var systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
var scopeObject = new Components.utils.Sandbox(systemPrincipal); 
// set properties of the scope object like this:
// scopeObject.someProperty = someValue;
var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
  .getService(Components.interfaces.mozIJSSubScriptLoader);
// Set uri to the uri of the script to load
loader.loadSubScript(uri, module, "UTF-8");
于 2013-05-26T10:23:50.643 回答