Is It Possible to Sandbox JavaScript Running In the Browser?

前端 未结 15 670
北海茫月
北海茫月 2020-11-22 13:58

I\'m wondering if it\'s possible to sandbox JavaScript running in the browser to prevent access to features that are normally available to JavaScript code running in an HTML

15条回答
  •  情歌与酒
    2020-11-22 14:37

    An ugly way but maybe this works for you , I took all the globals and redefined them in the sandbox scope , as well I added the strict mode so they can't get the global object using an anonymous function.

    function construct(constructor, args) {
      function F() {
          return constructor.apply(this, args);
      }
      F.prototype = constructor.prototype;
      return new F();
    }
    // Sanboxer 
    function sandboxcode(string, inject) {
      "use strict";
      var globals = [];
      for (var i in window) {
        // <--REMOVE THIS CONDITION
        if (i != "console")
        // REMOVE THIS CONDITION -->
        globals.push(i);
      }
      globals.push('"use strict";\n'+string);
      return construct(Function, globals).apply(inject ? inject : {});
    }
    sandboxcode('console.log( this, window, top , self, parent, this["jQuery"], (function(){return this;}()));'); 
    // => Object {} undefined undefined undefined undefined undefined undefined 
    console.log("return of this", sandboxcode('return this;', {window:"sanboxed code"})); 
    // => Object {window: "sanboxed code"}
    

    https://gist.github.com/alejandrolechuga/9381781

提交回复
热议问题