Created
November 13, 2013 00:45
-
-
Save nickjacob/7441600 to your computer and use it in GitHub Desktop.
an idea for a safe eval function
This file contains hidden or 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
function safe_eval(code, ctx) { | |
return (new Function (["window", "undefined"], "try { " + code + " } catch (e){ return e; }"))(ctx); | |
} | |
function restrict (base, perm) { | |
var out = {}, k = null, | |
READ = 'read', | |
WRITE = 'write', | |
RW = 'readwrite'; | |
for (k in perm) { | |
(function (key, val) { | |
if (!val) return; | |
if (perm[key] === READ) | |
out.__defineGetter__(key, function(){ return val; }); | |
else if (perm[key] === WRITE) | |
out.__defineSetter__(key, function (v){ base[key] = v; }); | |
else if (perm[key] === RW) | |
out[key] = val; | |
})(k, base[k]); | |
} | |
return out; | |
} | |
var READ = 'read', WRITE = 'write', RW = 'readwrite'; | |
// save eval with some window properties | |
safe_eval("console.log(window.document);", restrict(window, { document: READ })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey. This seems really cool. I'd like to have a tool like this.