这篇文章主要介绍“怎么实现JavaScript沙箱的基础功能”,在日常操作中,相信很多人在怎么实现JavaScript沙箱的基础功能问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么实现JavaScript沙箱的基础功能”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
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;
}
除了通信的能力之外,还额外要求了两个方法:
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
有以下几个问题:
4、web worker 实现
基本上,web worker
是一个受限的 js 运行时,以 js 为入口,和 iframe
差不多的通信机制
function evalByWebWorker(code: string) {
const blob = new Blob([code], { type: "application/javascript" });
const url = URL.createObjectURL(blob);
return new Worker(url);
}
evalByWebWorker(`
console.log('location.href: ', location.href)
// console.log('localStorage: ', localStorage)
`);
但同时,它确实比 iframe
要更好一点
5、quickjs 实现
使用 quickjs
的主要灵感来源于figma 构建插件系统的一篇博客,quickjs 中文文档
quickjs 是什么?它是一个 JavaScript 的运行时,虽然我们最常用的运行时是浏览器和 nodejs
,但也有许多其他的运行时,可以在 GoogleChromeLabs/jsvu 找到更多。而 quickjs
是其中一个轻量级、嵌入式、并且支持编译为 wasm
运行在浏览器上的一个运行时,同时它对 js 的特性支持到 es2020
(包括最喜爱的 Promise
和 async/await
)。
async function evalByQuickJS(code: string) {
const quickJS = await getQuickJS();
const vm = quickJS.createVm();
const res = vm.dump(vm.unwrapResult(vm.evalCode(code)));
vm.dispose();
return res;
}
console.log(await evalByQuickJS(`1+1`));
优点:
缺点:
到此,关于“怎么实现JavaScript沙箱的基础功能”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注天达云网站,小编会继续努力为大家带来更多实用的文章!