const sandboxProxy = (window, document) => {
const cloneDocument = document.cloneNode(true);
const cloneWindow = { ...window };
const proxyWindow = new Proxy(cloneWindow, {
has: function () {
return true;
},
get: function (target, key) {
if (key === Symbol.unscopables) return undefined;
return target[key];
},
set: function (target, key, value) {
target[key] = value;
return true;
}
});
const proxyDocument = new Proxy(cloneDocument, {
has: function () {
return true;
},
get: function (target, key) {
if (key === Symbol.unscopables) return undefined;
return target[key];
},
set: function (target, key, value) {
target[key] = value;
return true;
}
});
return {window:proxyWindow, document:proxyDocument};
};
function executeSandboxCode (){
const globalObject = sandboxProxy(window,document);
const sandboxfunction = new Function(`globalObject`,`with(globalObject){
return function(){
// 这就是沙箱代码
console.log('看看这个window',window);
console.log('看看这个document',document);
console.log('看看这个this',this);
}
}`);
sandboxfunction(globalObject).call(globalObject.window);
};
executeSandboxCode()