Background: I\'m working on a framework/library to be used for a specific site in coordination with greasemonkey/userscripts. This framework/library will al
I know this is an old post, but I just want to share an upgraded version of the Aadit M Shah solution, that seems to really sandbox without any way to access window (or window children): http://jsfiddle.net/C3Kw7/20/
// create our own local versions of window and document with limited functionality
var locals = {
window: {
},
document: {
}
};
var that = Object.create(null); // create our own this object for the user code
var code = document.querySelector("textarea").value; // get the user code
var sandbox = createSandbox(code, that, locals); // create a sandbox
sandbox(); // call the user code in the sandbox
function createSandbox(code, that, locals) {
code = '"use strict";' + code;
var params = []; // the names of local variables
var args = []; // the local variables
var keys = Object.getOwnPropertyNames( window ),
value;
for( var i = 0; i < keys.length; ++i ) {
//console.log(keys[i]);
locals[keys[i]] = null;
}
delete locals['eval'];
delete locals['arguments'];
locals['alert'] = window.alert; // enable alert to be used
for (var param in locals) {
if (locals.hasOwnProperty(param)) {
args.push(locals[param]);
params.push(param);
}
}
var context = Array.prototype.concat.call(that, params, code); // create the parameter list for the sandbox
//console.log(context);
var sandbox = new (Function.prototype.bind.apply(Function, context)); // create the sandbox function
context = Array.prototype.concat.call(that, args); // create the argument list for the sandbox
return Function.prototype.bind.apply(sandbox, context); // bind the local variables to the sandbox
}