Is this a possible solution for a pure javascript sandbox ? My willing is to execute an untrusted string of code without giving access to DOM, window, this, and so on but allowing the user to acces Math, JSON and other functionalities. I've tested it on Chrome.
UPDATE: I want to give the possibility to save on server user-defined code and make it available to other users. I'm looking for a way to deny access to the document ni order to make it safe.
function safe(code,args)
{
if (!args)
args=[];
return (function(){
for (i in window)
eval("var "+i+";");
return function(){return eval(code);}.apply(0,args);
})();
}
ff=function()
{
return 3.14;
}
console.log(safe("this;"));//Number
console.log(safe("window;"));//undefined
console.log(safe("console;"));//undefined
console.log(safe("Math;"));//MathConstructor
console.log(safe("JSON;"));//JSON
console.log(safe("Element;"));//undefined
console.log(safe("document;"));//undefined
console.log(safe("Math.cos(arguments[0]);",[3.14]));//-0.9999987317275395
console.log(safe("arguments[0]();",[ff]));//3.14
I've proposed it on an old post : https://stackoverflow.com/a/11513690/76081
Thanks!