欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Electron中打开和关闭子窗口以及子窗口向父窗口传值

发布时间:2025/3/19 编程问答 44 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Electron中打开和关闭子窗口以及子窗口向父窗口传值 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

场景

用HTML和CSS和JS构建跨平台桌面应用程序的开源库Electron的介绍以及搭建HelloWorld:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106413828

Electron怎样进行渲染进程调试和使用浏览器和VSCode进行调试:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106414541

在上面搭建好项目以及知道怎样进行调试后。学习怎样打开和关闭子窗口以及子窗口向父窗口传值。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

打开子窗口

在index.html中添加一个Button

<div><button id="popChildWindows">弹出子窗口</button> </div>

然后在js中获取这个button,并设置其点击事件

var btnPopChiildWin=document.getElementById('popChildWindows'); btnPopChiildWin.onclick = PopChiildWin;function PopChiildWin() {}

然后在项目下新建一个子窗口popup_page.html

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name= "viewport"content="width=device-width, initial-scale=1.0"><meta http-equiv= "X-UA-Compatible"content="ie=edge"><title>Document</title> </head> <body><h2>这是弹出的子窗口</h2><h2>公众号:霸道的程序猿</h2></body></html>

然后在上面js的点击事件中打开此窗口

    //打开子窗口  第一个参数是子窗口的路径  第二个参数是起的别名window.open('popup_page.html', "popup");

效果

 

关闭子窗口

在前面打开子窗口时获取窗口对象

let subWin; function PopChiildWin() {//打开子窗口  第一个参数是子窗口的路径  第二个参数是起的别名subWin = window.open('popup_page.html', "popup"); }

然后在html中新增一个button

<button id="closeChildWindows">关闭子窗口</button>

然后在js中设置其点击事件并关闭子窗口

var btnCloseChiildWin=document.getElementById('closeChildWindows'); btnCloseChiildWin.onclick = CloseChiildWin;function CloseChiildWin() {//关闭子窗口 subWin.close(); }

效果

 

子窗口向父窗口传值

在子窗口popup_page.html 中新建一个按钮并设置其点击事件

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><h2>这是弹出的子窗口</h2><h2>公众号:霸道的程序猿</h2><button onclick="sendMessageToParent()">向父窗口传递信息</button> </body> <script>function sendMessageToParent() {window.opener.postMessage({type: 1,message: "这是来自于子窗口的问候"});} </script> </html>

然后在父窗口所引用的js中通过

window.addEventListener("message", (msg) => {console.log("接收到的消息:", msg); })

接受消息

这里传送的消息是一个对象,效果如下

 

总结

以上是生活随笔为你收集整理的Electron中打开和关闭子窗口以及子窗口向父窗口传值的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。