Open onvno opened 5 years ago
<h1 id="test">this is index</h1> <iframe src="./iframePage.html" id='myframe'></iframe> <script> //获取iframe元素 iFrame = document.getElementById('myframe') //iframe加载完毕后再发送消息,否则子页面接收不到message iFrame.onload = function(){ //iframe加载完立即发送一条消息 iFrame.contentWindow.postMessage('MessageFromIndex1','*'); //iframe加载完再延迟1000ms发送一条消息 setTimeout(()=>{ iFrame.contentWindow.postMessage('MessageFromIndex2','*'); },1000) } const demo = document.getElementById('test'); demo.addEventListener('click', function(){ iFrame.contentWindow.postMessage('index click','*'); }) //回调函数 function receiveMessageFromIframePage (event) { console.log('index receiving:', event) } //监听message事件 window.addEventListener("message", receiveMessageFromIframePage, false);
<body style="border:5px solid #333;"> <h1 id="demo">this is iframePage</h1> <script> const demo = document.getElementById("demo"); demo.addEventListener('click', function(){ parent.postMessage( {msg: 'iframe click'}, '*'); }) //给父页面发送消息 parent.postMessage( {msg: 'MessageFromIframePage'}, '*'); //回调函数 function receiveMessageFromIndex ( event ) { // console.log( 'receiveMessageFromIndex', event ) console.log('iframe receiving:', event); } //监听message事件 window.addEventListener("message", receiveMessageFromIndex, false); </script> </body>
index内容
iframe内容