Is It Possible to Sandbox JavaScript Running In the Browser?

前端 未结 15 815
北海茫月
北海茫月 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:34

    I created a sandboxing library called jsandbox that uses web workers to sandbox evaluated code. It also has an input method for explicitly giving sandboxed code data it wouldn't otherwise be able to get.

    The following is an example of the API:

    jsandbox
        .eval({
          code    : "x=1;Math.round(Math.pow(input, ++x))",
          input   : 36.565010597564445,
          callback: function(n) {
              console.log("number: ", n); // number: 1337
          }
      }).eval({
          code   : "][];.]\\ (*# ($(! ~",
          onerror: function(ex) {
              console.log("syntax error: ", ex); // syntax error: [error object]
          }
      }).eval({
          code    : '"foo"+input',
          input   : "bar",
          callback: function(str) {
              console.log("string: ", str); // string: foobar
          }
      }).eval({
          code    : "({q:1, w:2})",
          callback: function(obj) {
              console.log("object: ", obj); // object: object q=1 w=2
          }
      }).eval({
          code    : "[1, 2, 3].concat(input)",
          input   : [4, 5, 6],
          callback: function(arr) {
              console.log("array: ", arr); // array: [1, 2, 3, 4, 5, 6]
          }
      }).eval({
          code    : "function x(z){this.y=z;};new x(input)",
          input   : 4,
          callback: function(x) {
              console.log("new x: ", x); // new x: object y=4
          }
      });
    

提交回复
热议问题