菜鸟-创作你的创作

JavaScript沙箱隔离示例代码

下面给你整理一份 JavaScript 沙箱隔离(Sandbox)常用实现方式 + 完整示例代码,包含:

这几种方式覆盖浏览器、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 的特点:


🔥 对比总结表

技术方案环境安全性适用场景
new Function + withJS 全环境❌弱Demo、简单隔离
Proxy 沙箱浏览器⭐⭐微前端、插件系统
iframe浏览器⭐⭐⭐⭐⭐最安全浏览器隔离
Node vmNode⭐⭐简单沙箱
VM2Node⭐⭐⭐⭐服务器端安全执行代码
ShadowRealm支持环境少⭐⭐⭐⭐未来趋势、完美隔离
退出移动版