場景
用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);
})
接受消息
這裏傳送的消息是一個對象,效果如下