JavaScript sandbox: hide global variables from a given area

I want to create an HTML + JS environment where the user can enter and run arbitrary JavaScript code that will be executed in the context of this jail object. I created a playground to illustrate what I have so far .

This does some decent work:

  • The main evaluation work:
    • Input: 2 + 2
    • Output: 4
  • this returns a jail object
    • Input: this
    • Output: [object Object]
  • this.hello() runs the expected method
    • Input: this.hello()
    • Output: hello world!
  • The user can configure their own functions and execute them later:
    • Input: this.foo = function() { return 42; }
    • Output: function () { return 42; }
    • Input: this.foo()
    • Ouput: 42
  • An attempt to access some object that I want to keep "hidden" from the prison context fails:
    • Input: hidden
    • Output: ReferenceError: hidden is not defined

However, it does not completely hide globally accessible properties, such as windowor documentfor the user:

  • Input: window
  • : [object Window]
  • : ReferenceError: window is not defined

, , - , , undefined null Jail, . , , , , . :

  • ? ?
  • , , -?
+4
1

, -; theyre , , Worker#terminate.

:

var worker = new Worker('path/to/evaluator.js');

:

worker.onmessage = function (e) {
    console.log(e.data);
};

:

worker.postMessage(someCode);

, :

onmessage = function (e) {
    postMessage(eval(e.data));
};

terminate , postMessage . ( , .)

- , , theyre , , .

XMLHttpRequest; . JavaScript- ? , .

+5

Source: https://habr.com/ru/post/1543152/


All Articles