父窗口与 iframe 子窗口之间的通信
父窗口:
- 获取 iframe 子窗口
var x = document.getElementById("myframe"); var y = x.contentWindow; // 子窗口 window 对象
- 发送消息
y.postMessage("我是A", '*');
- 监听子窗口发来的消息
window.addEventListener('message', function(eventObj){ });
子窗口
- 给父窗口发送消息
window.parent.postMessage(' ','*')
- 监听父窗口发来的消息
window.addEventListener('message', function(eventObj){ });
代码
- a.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>first electron</title> <script> function sendMessageToB() { var x = document.getElementById("myframe"); var y = x.contentWindow; y.postMessage("我是A", '*'); } window.addEventListener('message', function(eventObj){ console.log(document); document.getElementById('msgContainer').innerHTML = eventObj.data }); // 监听子窗口传递过来的数据,然后在界面上显示出来 </script> </head> <body> <input type="button" onclick="sendMessageToB()" value="向子窗口发送消息"><br> <div id="msgContainer"></div> <iframe id="myframe" src="b.html"> </body> </html>
- b.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button onclick="sendMsgToParent()">向父窗口传递信息</button> <div id="msgContainerB"></div> <script> function sendMsgToParent () { window.parent.postMessage('我是子窗口传递过来的信息,oh yeah','*') } window.addEventListener('message', function(e) { console.log(document.querySelector('#msgContainerB')); document.querySelector('#msgContainerB').innerHTML = e.data; }) </script> </body> </html>
结果
在父窗口中通过 window.open() 打开一个子窗口进行通信
父窗口
- 打开一个子窗口
var popup = window.open('b.html', 'title');
- 给子窗口发送消息,等待子窗口加载完成之后
popup.onload = function() { popup.postMessage('Hello World', '*'); };
- 监听子窗口发来的消息
window.addEventListener('message', function(e) { console.log(e); });
子窗口
- 给父窗口发送消息【当父窗口使用open方法打开子窗口的时候,只能使用opener找到父窗口,而不是parent】
window.opener.postMessage('Nice to see you', '*');
- 监听父窗口发来的消息
window.addEventListener('message', function(e) { console.log(e); });
代码
- a.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>first electron</title> </head> <body> <script> var popup = window.open('b.html', 'title'); popup.onload = function() { popup.postMessage('Hello World', '*'); }; window.addEventListener('message', function(e) { console.log(e); }); </script> </body> </html>
- b.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> window.opener.postMessage('Nice to see you', '*'); window.addEventListener('message', function(e) { console.log(e); }); </script> </head> <body> </body> </html>