The evalInSandbox()
function enables you to evaluate JavaScript code inside a sandbox you've previously created using the Components.utils.Sandbox
constructor.
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("https://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 "https://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.