跳到主要内容

1 篇博文 含有标签「Sandbox」

查看所有标签

· 阅读需 1 分钟

const sandboxProxies = new WeakMap()
function compileCode(src) {
src = "with (sandbox) {" + src + "}";
const code = new Function("sandbox", src);

function has (target, key) {
// 给予调用外界console的权力
if (['console'].includes(key)) {
return target[key]
}

// 对于其他属性,单独要做检查
if (!target.hasOwnProperty(key)) {
throw new ReferenceError(`${key} is not defined`)
}

// 对于未知特殊情况,就假设属性存在于内部做兜底
return true;
}

return function (sandbox) {
// 设置缓存,减少Proxy的实例化
if (!sandboxProxies.has(sandbox)) {
const sandboxProxy = new Proxy(sandbox, { has });
sandboxProxies.set(sandbox, sandboxProxy)
}

return code(sandboxProxies.get(sandbox));
};
}

globalParam = "globalParam";
let outside = "outside";

compileCode(`
let inside = 'inside'
console.log('inside') // ok
console.log(preset) // ok
console.log(globalParam) // error
console.log(outside) // error
`)({ preset: "preset" });