BrowserWindow打开新窗口
remote模块的使用
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
一、remote模块
最新的electron版本中,remote的模块已被废弃,但在渲染进程中使用BrowserWindow模块时,需要使用remote模块进行调用。
在remote模块被废弃后,BrowserWindow的调用采用以下模式
1.引入BrowserWindow模块
const electron = require("electron")
const BrowserWindow = electron.BrowserWindow
2.初始化remote模块
// 打开新窗口 BrosweWindow 初始化
require('@electron/remote/main').initialize();
require("@electron/remote/main").enable(mainWindow.webContents);
3.在渲染进程中调用
const { BrowserWindow } = require('@electron/remote')
二、完整代码实现
1.html页面
主页面 index.html
代码如下(示例):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1>💖 Hello World!</h1>
<button id = "btn">打开新窗口</button>
<script src="render.js"></script>
</body>
</html>
新窗口页面 new.html
代码如下(示例):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1>💖 新闻页面 </h1>
</body>
</html>
2. 主进程 main.js
代码如下(示例):
const { app } = require('electron');
const electron = require("electron")
const BrowserWindow = electron.BrowserWindow
const path = require('path');
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
app.quit();
}
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences:{
// 浏览器 js 可以支持 node 接口
// 渲染进程(rendee.js)中可以使用 nodejs 几口
nodeIntegration: true,
contextIsolation:false,
enableRemoteModule: true, // 启用remote模块
},
});
// 打开新窗口 BrosweWindow 初始化
require('@electron/remote/main').initialize();
require("@electron/remote/main").enable(mainWindow.webContents);
mainWindow.loadFile(path.join(__dirname, 'index.html'));
mainWindow.webContents.openDevTools();
};
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
3. 渲染进程 render.js
代码如下(示例):
const {remote} = require("electron")
// const BrowserWindow = remote.BrowserWindow;
const { BrowserWindow } = require('@electron/remote')
const path = require("path");
window.onload=()=>{
var btn = document.querySelector("#btn")
btn.onclick=()=>{
// alert("12345");
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences:{
// 浏览器 js 可以支持 node 接口
// 渲染进程(rendee.js)中可以使用 nodejs 几口
nodeIntegration: true,
contextIsolation:false,
enableRemoteModule: true, // 启用remote模块
},
});
mainWindow.loadFile(path.join(__dirname, 'new.html'));
}
}
三、实现效果
总结
点击打开新窗口按钮,即可打开新的窗口