美文网首页
JS iframe 利用 postMessage 与主窗口通信

JS iframe 利用 postMessage 与主窗口通信

作者: 风之化身呀 | 来源:发表于2019-11-26 14:24 被阅读0次
iframe与父级通信

1、父级 => iframe

// html
<iframe id="iframe" src="http://localhost:8080/" width="100%" height="100%" frameborder="0"></iframe>
// js
const iframeRef = <HTMLIFrameElement>document.getElementById('iframe')
if (iframeRef) {
   iframeRef.contentWindow.postMessage({ action: 'hide', params: { name: 1 } }, 'http://localhost:8080')
}
window.addEventListener('message', function(e) {
      if (e.origin === 'http://localhost:4300') {
        console.log(e.data)
      }
})

2、iframe => 父级

  • iframe 侧代码
const parent = window.parent
parent.postMessage('test','http://localhost:4300')
  • 父级侧代码
window.addEventListener('message', function(e) {
      if (e.origin === 'http://localhost:8080') {
        console.log(e.data)  // test
      }
})

相关文章

网友评论

      本文标题:JS iframe 利用 postMessage 与主窗口通信

      本文链接:https://www.haomeiwen.com/subject/euuewctx.html