您当前的位置:首页 > 网站建设 > javascript
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 | ajax | jQuery | 小程序 |

JavaScript 沙箱探索

51自学网 2022-02-21 13:38:41
  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;}

除了通信的能力之外,还额外要求了两个方法:

  • 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 有以下几个问题:

万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。