JS iframe 利用 postMessage 与主窗口通信
2019-11-26 本文已影响0人
风之化身呀

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')
}
- iframe 侧代码 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
}
})