1

There is a need to perform an anonymous function (on the client) to a limited scope with its own environment variables (without access to the global variables). Overriding context this is not a problem, but with variable I see only one option - a eval. But as eval should be left to the edge, I decided to ask the community if there are other solutions to the problem.

Actually the problem:

function sandbox(fn){ // with eval
   fn = fn.toString();
   // need to dynamically create variables inside fn 
   fn = '(function(){"use strict"; var window, document; (' + fn + ').call(this);}) ';
   fn = eval(fn);
   fn.call({}); // example
}

sandbox(function(){
   console.log(window, document, this); // return undefined, undefined, Object {}
});

For a redefinition of the variables must respond to the function sandbox(). I mean the one with a clear redefinition of variables within functions are not transmitted to offer. Dining with the dynamic creation of the frame with its own environment, as well as transferring variable parameters to a function

(function(window, document){...})(null, null)

also not suitable for it, and so everything is clear, and is needed here dynamization of this process by the sandbox(). There are other ways to solve without using eval?

Thanks in advance.

vldmir
  • 31
  • 2
  • possible duplicate of [Is It Possible to Sandbox JavaScript Running In the Browser?](http://stackoverflow.com/questions/195149/is-it-possible-to-sandbox-javascript-running-in-the-browser) – Jeremy J Starcher Aug 16 '14 at 23:43
  • Note, the eval solution doesn't actually protect `window` or `document`. E.g. suppose `fn = ")};window.close()//"` – p.s.w.g Aug 16 '14 at 23:43
  • @vldmir - Nicely asked question, BTW. But there are some great answers out there already for it. – Jeremy J Starcher Aug 16 '14 at 23:43
  • @p.s.w.g - This is example. You can override all methods of window. The question is, how to do without eval. – vldmir Aug 16 '14 at 23:45
  • @Jeremy J Starcher - I'm interested in the possible implementation of the native methods – vldmir Aug 16 '14 at 23:55

0 Answers0