Skip to content

Instantly share code, notes, and snippets.

@nickjacob
Created November 13, 2013 00:45
Show Gist options
  • Save nickjacob/7441600 to your computer and use it in GitHub Desktop.
Save nickjacob/7441600 to your computer and use it in GitHub Desktop.
an idea for a safe eval function
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 }));
@SephReed
Copy link

Hey. This seems really cool. I'd like to have a tool like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment