下面给你整理一份 JavaScript 沙箱隔离(Sandbox)常用实现方式 + 完整示例代码,包含:
- 基于
new Function的基本沙箱 - 使用
Proxy的增强沙箱 - 使用
iframe的浏览器沙箱 - 使用
VM2的 Node.js 沙箱 - 使用
Realm/ShadowRealm的现代沙箱示例
这几种方式覆盖浏览器、Node.js,以及实际工程常用的沙箱技术。
✅ 1. 基于 new Function 的基础沙箱(最简单)
这种方式通过 限制外部变量访问 来实现简单沙箱。
function createSandbox(code) {
return new Function("sandbox", `
with (sandbox) {
return eval(\`${code}\`)
}
`);
}
const sandbox = { console };
const run = createSandbox("console.log('沙箱运行成功!'); 1 + 2");
console.log(run(sandbox)); // 输出:3
⚠️ 缺点:with + eval 容易被逃逸,不算真正安全,只适合基础隔离。
✅ 2. Proxy + with 完整沙箱(前端框架常用,如 Qiankun)
这是前端常用技术,用 Proxy 模拟全局对象,阻断 window 污染。
function createProxySandbox() {
const fakeWindow = {};
return new Proxy(fakeWindow, {
get(target, key) {
if (key === "window") return fakeWindow;
return target[key] ?? window[key];
},
set(target, key, value) {
target[key] = value; // 限制污染 window
return true;
}
});
}
const sandbox = createProxySandbox();
(function (window) {
window.test = "from sandbox";
console.log(window.test);
})(sandbox);
console.log(window.test); // undefined:未污染全局
▶ 实战用途:
微前端框架(如 qiankun、single-spa)大量使用这种沙箱方法。
✅ 3. 使用 iframe 沙箱(浏览器最安全办法之一)
浏览器中的 最佳隔离方式就是 iframe。
HTML
<iframe id="sandbox" sandbox="allow-scripts"></iframe>
JS
const iframe = document.getElementById('sandbox');
// 执行沙箱代码
iframe.contentWindow.eval(`
console.log('Iframe sandbox works!');
window.a = 123;
`);
console.log(window.a); // undefined
▶ 优点:
- 完全隔离作用域
- 安全性最强(浏览器隔离)
✅ 4. Node.js 中使用 vm 模块沙箱
Node 官方内置的沙箱模块。
const vm = require("vm");
const sandbox = { counter: 0 };
vm.createContext(sandbox);
const code = `
counter += 1;
"执行结果:" + counter;
`;
const result = vm.runInContext(code, sandbox);
console.log(result); // 执行结果:1
console.log(sandbox.counter); // 1
⚠️ 注意:
Node 内置 vm 不是完全安全,推荐使用 vm2。
✅ 5. 使用 VM2(Node.js 生产级沙箱)
const { VM } = require('vm2');
const vm = new VM({
timeout: 1000,
sandbox: { x: 1 }
});
const result = vm.run(`
x = x + 5;
x;
`);
console.log(result); // 6
VM2 是 Node 里最安全的沙箱之一(但历史上也有漏洞)。
✅ 6. 使用 ShadowRealm(新标准,真正隔离生态)
部分环境已支持 ShadowRealm(更安全的 ES 隔离)。
const realm = new ShadowRealm();
realm.evaluate(`
globalThis.value = 100;
console.log("来自 ShadowRealm:", value);
`);
ShadowRealm 的特点:
- 完全隔离作用域
- 没有共享 window / globalThis
- 原生安全
🔥 对比总结表
| 技术方案 | 环境 | 安全性 | 适用场景 |
|---|---|---|---|
| new Function + with | JS 全环境 | ❌弱 | Demo、简单隔离 |
| Proxy 沙箱 | 浏览器 | ⭐⭐ | 微前端、插件系统 |
| iframe | 浏览器 | ⭐⭐⭐⭐⭐ | 最安全浏览器隔离 |
| Node vm | Node | ⭐⭐ | 简单沙箱 |
| VM2 | Node | ⭐⭐⭐⭐ | 服务器端安全执行代码 |
| ShadowRealm | 支持环境少 | ⭐⭐⭐⭐ | 未来趋势、完美隔离 |