Skip to content

Instantly share code, notes, and snippets.

@line-o
Created October 6, 2012 19:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save line-o/3845819 to your computer and use it in GitHub Desktop.
Save line-o/3845819 to your computer and use it in GitHub Desktop.
Evaluate JavaScript code in a configurable Sandbox (no Iframes here)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Frameless JS-Sandbox</title>
<style>
textarea,
button {
float:left;
}
textarea {
font-size: 2em;
}
button {
padding: 2em;
line-height: .2em;
font-size: 2.9em;
}
</style>
</head>
<body>
<form id="the_form" action="#">
<!-- paste your code to test in here -->
<textarea id="the_script" rows="5" cols="30">eval("alert(1);");</textarea>
<button type="submit">Evaluate</button>
</form>
<script src="SandBox.js"></script>
<script>
SandBox.init('the_form', 'the_script', {
'window': {
'alert': console.log.bind(console), // your
'Function': console.warn.bind(console), // callbacks
'eval': console.warn.bind(console), // here
}
});
</script>
</body></html>
var SandBox = (function (realCtx) {
var get = realCtx.document.getElementById.bind(realCtx.document),
_evil = eval;
return {
init: function (form, script, ctx) {
this._form = get(form);
this._script = get(script);
this.fakeCtx = ctx;
this._form.onsubmit = SandBox.evaluate;
window.onerror = function (msg, file, line) {
// handle error here
if (msg.indexOf("'eval' of null")) {
msg = 'function.apply() or function.call() with null';
// check for this file
console.warn(msg);
// suppress error
}
};
},
evaluate: function(e) {
var run = function (ctx, script) {
for (p in ctx.window) {
ctx[p] = ctx.window[p];
}
_evil("with (SandBox.fakeCtx) { (function () { 'use strict'; " + script + "})(); }");
};
run.call({}, SandBox.fakeCtx, SandBox._script.value);
e.preventDefault();
}
};
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment