JSandBox: an efficient and safe sandbox for JavaScript
JSandBox is an efficient and safe sandbox for JavaScript, where some JS code is executed in a safe environment. Actually, JSandBox is able to detect several problems your JS code could be affected by.
How does it work?
First, your JS code is parsed for finding dangerous/not desirable functions, like eval,
alert, Function() or a custom one. Then, your code is
executed on a local web worker, so in a safe environment, in order to find some syntax errors, or
infinite loops.
If no problems are detected, you are able to safely execute your JS code.
You can try it here.
Usage
Clone the repository:
$ git clone git@github.com:lukesmolo/JSandBox.git
Include JSandBox in your page:
<script type="text/javascript" src="JSandBox.js"></script>You have to include JQuery too.
Call JSandBox on the code you want to check.
var code = 'alert("hello world")';
//with default settings
code.JSandBox();
//or with custom settings
code.JSandBox({
'check_functions': false,
'worker': 'js/JSandBox-worker.js',
'functions': ['alert', 'eval', 'Function', 'myFunc'],
'callback': myCallback
});
By default, JSandBox have these options enabled:
var settings = {
'check_functions': true,
'check_syntax': true,
'check_loops': true,
'functions': ['alert', 'eval', 'Function'],
'worker': 'JSandBox-worker.js',
'timeout' : 2000,
'callback' : null
};check_functions, check_syntax, check_loops
specify which features are enabled. You can disable what you want, but please, take into account that check_loops requires check_syntax too. Also remember that without check_loops enabled, your worker could loop forever.
functions
specify which functions are not allowed. For example:
['alert', 'eval', 'Function', 'myFunc']
worker
specify the path of the web worker. According to http://www.w3.org/TR/workers/:
When the Worker(scriptURL) constructor is invoked, the user agent must run the following steps:
1) Resolve the scriptURL argument relative to the entry script's base URL, when the method is invoked.
timeout
specify the timeout after which worker will be stopped.
callback
specify a callback for returning your JS code status. By default, there is a simple alert. A callback has to be defined in this way:
function myCallback(msg, error)msg is a string containing the description of the returned status, error is a flag set when there is a problem.
Demo
You can find a demo here.
License
JSandBox is released under the MIT License.