JS iframe 利用 postMessage 与主窗口通信

2019-11-26  本文已影响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 => 父级

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
      }
})
上一篇 下一篇

猜你喜欢

热点阅读