
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
}
})
网友评论