📦 Make a sandbox for a function, isolating the function's effects, blocking outer-scoped variables (e.g. window
, global
) and dangerious operations (e.g. eval()
, new Function()
).
All the module exports is a main function.
Input/Output
input (parameter)
A function or string of a function.
output (return)
A function or string of a function.
Installation
$ npm install --save function-sandbox
Usage
example
const fnsb = ; let a = 1; let { console;// ^ console;// ^ { console; console;// ^ console;// ^ console;// ^ ;// ^ 'console.log("using new Function()")';// ^ } var F = fconstructor; 'console.log("using new Function()")';// ^ var d = 1; return ;}; let f2 = ; // `f2` is function; // => 2 undefined 1 undefined {} {}console; // => 1 let f3 = ; // `f3` is string
Now f3
is such a string of a function:
"function () { var window = {}, global = {}, process = {}, Function = function () { return function () {} }, eval = function () {}; return (function (b) {
'use strict';
var a, c, e;
... Here is the original function body ...
}).apply(null, arguments); }"
options
The second parameter is optional and can be either Boolean or Object. When it is true
, the main function will return a function instead of a string. When it is an object, it has several properties to be set:
property | value | example |
---|---|---|
asFunction | Boolean, whether to return a function or a string. | true |
whiteList | Array, a list of variable names not to be blocked. | ['$'] ['Promise', 'JSON'] |
injection | Object, a map from variable name to value. | { a: 1, b: function (x) { return x * x; } } |
More Related
- The Function in JavaScript.
- Node.js vm.
- Web Worker.
License
Copyright © 2018-present, shenfe