WebAssembly 在浏览器端代码执行中的应用
Applying WebAssembly for In-Browser Code Execution
| iDev Engineering | 2026-08-27T11:11:23
iDev 前端团队使用 WebAssembly 技术在浏览器端实现了安全的多语言代码沙箱,支持 Python、JavaScript 和 Rust 代码的即时执行和结果预览。
iDev frontend team implemented a secure multi-language code sandbox in the browser using WebAssembly technology, supporting instant execution and result preview for Python, JavaScript, and Rust code.
需求背景iDev 在线编辑器需要为用户提供代码即时运行能力,传统方案需要后端沙箱服务器,带来延迟和成本问题。WebAssembly 让我们能在浏览器端安全地执行代码。技术方案语言运行时移植Python:使用 Pyodide(CPython 编译为 Wasm),支持 NumPy、Pandas 等科学计算库JavaScript:基于 QuickJS 的 Wasm 编译版本,完全沙箱隔离Rust:使用 wasm-pack 将用户代码编译为 Wasm 模块安全沙箱所有代码在 Web Worker 中运行,与主线程完全隔离。通过 SharedArrayBuffer 实现内存限制,设置 CPU 时间上限防止无限循环:const worker = new Worker('sandbox-worker.js'); const timeout = setTimeout(() => worker.terminate(), 10000); worker.postMessage({ code: userCode, lang: 'python' }); worker.onmessage = (e) => { clearTimeout(timeout); displayResult(e.data); };性能优化Pyodide 运行时首次加载约 12MB,通过 Service Worker 缓存和 CDN 预热,二次加载时间低于 500ms。NumPy 等常用库预编译为 Wasm 包,按需加载。文件系统模拟使用 Emscripten 的 MEMFS 模拟文件系统,用户代码可以正常使用文件读写 API。持久化数据存储在 IndexedDB 中。效果与展望浏览器端代码执行的平均延迟低于 200ms(不含首次加载),用户无需等待远程服务器响应。下一步计划支持 Go 和 Java(通过 TeaVM)。
BackgroundiDev's online editor needs to provide users with instant code execution capability. Traditional approaches require backend sandbox servers, introducing latency and cost issues. WebAssembly enables us to safely execute code in the browser.Technical ApproachLanguage Runtime PortingPython: Using Pyodide (CPython compiled to Wasm), supporting NumPy, Pandas, and other scientific computing librariesJavaScript: Wasm-compiled version based on QuickJS, fully sandboxedRust: Using wasm-pack to compile user code into Wasm modulesSecurity SandboxAll code runs in Web Workers, completely isolated from the main thread. Memory limits are enforced via SharedArrayBuffer, with CPU time caps to prevent infinite loops:const worker = new Worker('sandbox-worker.js'); const timeout = setTimeout(() => worker.terminate(), 10000); worker.postMessage({ code: userCode, lang: 'python' }); worker.onmessage = (e) => { clearTimeout(timeout); displayResult(e.data); };Performance OptimizationPyodide runtime initial load is approximately 12MB. Through Service Worker caching and CDN warm-up, subsequent load times are under 500ms. Common libraries like NumPy are pre-compiled to Wasm packages and loaded on demand.File System SimulationWe use Emscripten's MEMFS to simulate the file system, allowing user code to use file read/write APIs normally. Persistent data is stored in IndexedDB.Results and Future PlansBrowser-side code execution average latency is under 200ms (excluding first load), with users experiencing no wait for remote server responses. Next steps include supporting Go and Java (via TeaVM).