MicroApp 源码
Iframe 沙箱
源码:https://github.com/micro-zoe/micro-app/blob/dev/src/sandbox/iframe/index.ts
constructor
备注
创建 iframe 沙箱:
- 执行 createIframeElement 方法:在沙箱中创建了一个iframe Element并插入到了document中,并且返回了相关销毁当前 iframe 的方法给到字段  this.deleteIframeElement
- 定义代理的 window this.microAppWindow为新建的iframe Element的contentWindow
- 执行 patchIframe 方法
patchIframe 做了什么?
定义了 this.sandboxReady 字段,通过条件判断(当前microAppWindow和上一次microAppWindow不相同)执行 callback function(之前会先执行一次 microAppWindow.stop())
patchIframe callback function
// create new html to iframe - 在 iframe 中创建了一个新的 html
this.createIframeTemplate(this.microAppWindow)
// get escapeProperties from plugins - 获取插件数据存放到 this.escapeProperties 字段中
this.getSpecialProperties(appName)
// patch location & history of child app - 创建代理路由
this.proxyLocation = patchRouter(appName, url, this.microAppWindow, browserHost)
// patch window of child app
this.windowEffect = patchWindow(appName, this.microAppWindow, this)
// patch document of child app
this.documentEffect = patchDocument(appName, this.microAppWindow, this)
// patch Node & Element of child app
patchElement(appName, url, this.microAppWindow, this)
/**
 * create static properties
 * NOTE:
 *  1. execute as early as possible
 *  2. run after patchRouter & createProxyWindow
 */
this.initStaticGlobalKeys(appName, url, this.microAppWindow)
patchRouter
export function patchRouter (
  appName: string,
  url: string,
  microAppWindow: microAppWindowType,
  browserHost: string,
): MicroLocation {
  // 重新建一个新的 url location
  const childStaticLocation = createURL(url)
  const childHost = childStaticLocation.protocol + '//' + childStaticLocation.host
  const childFullPath = childStaticLocation.pathname + childStaticLocation.search + childStaticLocation.hash
  // rewrite microAppWindow.history
  const microHistory = microAppWindow.history
  microAppWindow.rawReplaceState = microHistory.replaceState
  assign(microHistory, createMicroHistory(appName, microAppWindow.location))
  /**
   * Init microLocation before exec sandbox.start
   * NOTE:
   *  1. exec updateMicroLocation after patch microHistory
   *  2. sandbox.start will sync microLocation info to browser url
   */
  updateMicroLocation(
    appName,
    childFullPath,
    microAppWindow.location,
    'prevent'
  )
  // create proxyLocation
  return createMicroLocation(
    appName,
    url,
    microAppWindow,
    childStaticLocation,
    browserHost,
    childHost,
  )
}