1、场景最近基于 web 在做一些类似于插件系统一样的东西,所以折腾了一下 js 沙箱,以执行第三方应用的代码。
2、沙箱基础功能在实现之前(好吧,其实是在调研了一些方案之后),确定了沙箱基于 event bus 形式的通信实现上层的功能,基础的接口如下 export interface IEventEmitter { /** * 监听事件 * @param channel * @param handle */ on(channel: string, handle: (data: any) => void): void; /** * 取消监听 * @param channel */ offByChannel(channel: string): void; /** * 触发事件 * @param channel * @param data */ emit(channel: string, data: any): void;}/** * 一个基本 js vm 的能力 */export interface IJavaScriptShadowbox extends IEventEmitter { /** * 执行任意代码 * @param code */ eval(code: string): void; /** * 销毁实例 */ destroy(): void;} 除了通信的能力之外,还额外要求了两个方法: eval : 执行一段 js 代码 destroy : 销毁沙箱,供内部实现处理一些清理任务 JavaScript 沙箱示意图: 
下面吾辈将分别演示使用 iframe/web worker/quickjs 执行任意 js 的方法
3、iframe 实现老实说,谈到 web 中的沙箱,可能第一时间想到的就是 iframe 了,但它是以 html 作为入口文件,而非 js,这对于希望将 js 作为入口而不一定需要显示 iframe 的场景而言就不甚友好了。 
当然可以将 js 代码包裹到 html 中然后执行 function evalByIframe(code: string) { const html = `<!DOCTYPE html><body><script>$[code]</script></body></html>`; const iframe = document.createElement("iframe"); iframe.width = "0"; iframe.height = "0"; iframe.style.display = "none"; document.body.appendChild(iframe); const blob = new Blob([html], { type: "text/html" }); iframe.src = URL.createObjectURL(blob); return iframe;}evalByIframe(`document.body.innerHTML = 'hello world'console.log('location.href: ', location.href)console.log('localStorage: ',localStorage)`); 但 iframe 有以下几个问题: |