iframe 通信

74 阅读1分钟

项目背景

A平台是vue2开发的,B平台是用vue3开发的,现在产品提了一个需求,想要在A平台嵌入B平台页面。

重新用vue2开发那是不可能的,因此考虑用iframe 来实现

iframe 与 上级的通信

iframe -> top

示例:iframe 通知top 已初始化完成

iframe 传值

const data = 'init'
window.parent.postMessage(data, '*');

top 接收

window.addEventListener('message', function(event) {
  if (event.data === 'init') {
    // todo
  }
})

top -> iframe

top 传值

const data = 'Hello, iframe!';
const iframe = document.getElementById('linker-iframe') as HTMLIFrameElement;
const iframeWindow = iframe.contentWindow as Window;
window.addEventListener('message', function(event) {
  if (event.data === 'init') {
    // 下面这句是关键
    iframeWindow.postMessage(data, '*');
  }
})

iframe 接收

window.addEventListener('message', function(event) {
  // todo
})

遇到问题

A平台打开页面时有短暂的空白

增加loading