准备工作
- 创建一个文件夹,建立
content.html
和test.html
文件 - 使用VSCode打开这个文件夹
代码
- test.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> <div> <button onclick="openSonWindow()">打开子窗口 window.open</button> </div> <div id="msgContainer"></div> </body> <script> // 打开一个子窗口 function openSonWindow () { // window.open('https://hbiao68.blog.csdn.net/') window.open('content.html') } setInterval(window.addEventListener('message', (eventObj) => { document.querySelector('#msgContainer').innerHTML = eventObj.data })); // 监听子窗口传递过来的数据,然后在界面上显示出来 </script> </html>
- content.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> </body> <script> function sendMsgToParent () { console.log(11111); window.opener.postMessage('我是子窗口传递过来的信息,oh yeah') console.log(2222); } </script> </html>
- 在
test.html
上,右键,点击Open With Live Server
- 点击按钮就可以进行通信啦
- oye,成功