www 编辑

The evalInSandbox() function enables you to evaluate JavaScript code inside a sandbox you've previously created using the Components.utils.Sandbox constructor.

Note: It's not safe to use evalInSandbox() to evaluate JSON strings; instead, use the techniques discussed in the article on JSON. You can also find Firefox 3.5 specific information in Using JSON in Firefox.

Use

To use evalInSandbox(), you must first create a sandbox object using its constructor, Components.utils.Sandbox. In the constructor you define the security principal for code running in the sandbox, and can make various properties available to code running in the sandbox.

The sandbox will become the global scope object when you pass it to evalInSandbox(text, sandbox).

You can import functions or objects into the sandbox simply by assigning them to the sandbox object.  For example:

function double(n) {
  return  n * 2;
}

// create new sandbox instance
var mySandbox = new Components.utils.Sandbox("http://www.example.com/");
mySandbox.y = 5;  // insert property 'y' with value 5 into global scope.
mySandbox.double = double;
var result = Components.utils.evalInSandbox("x = y + 2; double(x) + 3", mySandbox);

console.log(result);             // 17
console.log(mySandbox.x);        //  7

Operations on objects you insert into this sandbox global scope do not carry privileges into the sandbox:

mySandbox.foo = Components;
// this will give a "Permission Denied" error
Components.utils.evalInSandbox("foo.classes", mySandbox);

Optional Arguments

You can optionally specify the JS version, filename, and line number of the code being evaluated. For instance:

var x = Components.utils.evalInSandbox(
  "let x = 1;",
  sandbox,
  "1.8", // "latest" is recognized as a special case
  "http://foo.com/mycode.js",
  25
);

The above will execute code using JavaScript 1.8.  Any exceptions raised by the evaluated code will show as originating from the above URL.  The evaluated code is assumed to start at line 25 of the document at that URL.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:113 次

字数:2916

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文