4、electron打开子窗口

1、安装remote模块

npm install @electron/remote --save

2、主进程index.js

 1 var electron = require('electron')
 2 
 3 var app = electron.app   //引用APP
 4 var BrowserWindow = electron.BrowserWindow;  //窗口引用
 5 var mainWindow = null;  //声明要打开的主窗口
 6 
 7 app.on('ready',()=>{
 8     mainWindow = new BrowserWindow({
 9         width:800,
10         height:800,
11         webPreferences:
12         {
13             nodeIntegration:true,
14             contextIsolation:false,
15             enableRemoteModule: true,  //允许使用remote模块
16         }
17     });
18 
19     require("@electron/remote/main").initialize();  //初始化remote模块
20     require("@electron/remote/main").enable(mainWindow.webContents);  //
21 
22     //mainWindow.loadFile('index.html');
23     mainWindow.loadFile('打开新窗口.html');
24     //mainWindow.openDevTools();
25     mainWindow.on('close',()=>{
26         mainWindow = null;   //关闭窗口释放资源
27     })
28 });
View Code

3、打开新窗口.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>Document</title>
 8 </head>
 9 <body>
10     <input type="button" id="btn" value="打开新窗口" />
11 
12     <script>
13         const BrowserWindow = require("@electron/remote").BrowserWindow;
14         const btn = document.querySelector("#btn");
15 
16         window.onload = function(){
17             btn.onclick = function(){
18                 newWin = new BrowserWindow({
19                     width:500,
20                     height:500
21                 });
22                 newWin.loadFile('子窗口.html');
23                 newWin.on("closed",()=>{
24                     newWin = null;
25                 })
26             }
27         }
28     </script>
29 </body>
30 </html>
View Code

4、子窗口.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>Document</title>
 8 </head>
 9 <body>
10     <h1>我是子窗口</h1>
11 </body>
12 </html>
View Code

5、运行效果

 

posted @ 2022-12-08 17:22  ziff123  阅读(898)  评论(0编辑  收藏  举报