Electron中打开和关闭子窗口以及子窗口向父窗口传值
生活随笔
收集整理的這篇文章主要介紹了
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中打开和关闭子窗口以及子窗口向父窗口传值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Electron中实现通过webview
- 下一篇: Winform中实现序列化指定类型的对象