Perhaps this is not what you are looking for, but what if, instead of passing a string to your sandbox, you pass a function. It even allows you to use eval for source files.
Your code will work as follows:
... Sandbox.prototype.Run = function(fn){ fn.call(this); } var bx = new Sandbox(); bx.run(function(){ this.x = 1; }); bx.getVar("x")
then if you want to use eval all you need to do is write a function to add function syntax
this.x = 1; this.blah = "Hello, World!";
FROM
Sandbox.prototype.evaluate = function(src){ return eval("function(){" + src + "}"); } bx.Run(Sandbox.evaluate(src)); bx.getVar("x")
In addition, using this method, you can transfer objects and functions of the sandboxed code using them, passing them to functions that will simulate a completely new pseudo-environment for work.
Edit: I did a little research on the answer perfect to your question, which
Is it possible to iterate over variables declared in a local scope?
And the answer is fooobar.com/questions/254772 / .... This seems to be a javascript limitation at the moment. Hope something similar appears in the new specification.
My idea at this point would be to evaluate the source so that all var instructions go to the window object, which with some effort could be repeated and manually added to the Sandbox object.
Like this Warning: terribly simplified
(function(){ var src = get_source_file(); eval(src); iterate_over_each_newly_created_window_property(function(property, value){ bx[property] = value; window[property] = undefined; }); })();
Edit 2: MY IDEA WORKS =)
function Sandbox(){ return this; } Sandbox.prototype.run = function(src){ // Take a snapshopt of the window object before var before = {}; var prop; for(prop in window){ before[prop] = true; } // Then evaluate the source window.eval(src); // Then see what changed var changed = []; for(prop in window){ if(!before[prop]){ // Add to the sandbox object this[prop] = window[prop]; delete window[prop]; } } } var bx = new Sandbox(); bx.run("var x = 'Hello, World!';"); alert(bx.x);
Working example (jsFiddle)
function Sandbox(){ this.keys = []; this.values = []; return this; } Sandbox.prototype.eval = function(src){ var before = {}, prop, fn;
Edit 3: Bug fixed according to your requirements
Now I know that it has errors and some functions that can make it escape. Now it’s your job to clear the code for real use. I gave you conceptually how to do this.