Created
October 6, 2012 19:09
-
-
Save line-o/3845819 to your computer and use it in GitHub Desktop.
Evaluate JavaScript code in a configurable Sandbox (no Iframes here)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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