如何在 Electron 中创建一个新窗口,并在该窗口中接收来自主进程的消息
如何在 Electron 中创建一个新窗口,并在该窗口中接收来自主进程的消息 ### 1. 主进程代码(main.js)const { app, BrowserWindow, ipcMain } = require('electron');
function createMainWindow() {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
});
mainWindow.loadFile('index.html');
// 监听来自渲染进程的消息
ipcMain.on('message-from-renderer', (event, arg) => {
console.log('Received message from renderer:', arg);
// 创建一个新窗口
const newWindow = new BrowserWindow({
width: 400,
height: 300,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
});
// 加载新窗口的 HTML 文件
newWindow.loadFile('newWindow.html');
// 将消息发送到新窗口
newWindow.webContents.on('did-finish-load', () => {
newWindow.webContents.send('message-from-main', arg);
});
});
}
app.whenReady().then(createMainWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createMainWindow();
}
});
### 2. 渲染进程代码(index.html)
html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>主窗口</title>
</head>
<body>
<h1>主窗口</h1>
<button id="sendMessage">发送消息到主进程</button>
<script>
const { ipcRenderer } = require('electron');
document.getElementById('sendMessage').addEventListener('click', () => {
// 发送消息到主进程
ipcRenderer.send('message-from-renderer', '你好,主进程!');
});
</script>
</body>
</html>
### 3. 新窗口的 HTML 文件(newWindow.html)
html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>新窗口</title>
</head>
<body>
<h1>新窗口</h1>
<div id="message"></div>
<script>
const { ipcRenderer } = require('electron');
// 监听来自主进程的消息
ipcRenderer.on('message-from-main', (event, arg) => {
document.getElementById('message').innerText = '收到的消息: ' + arg;
});
</script>
</body>
</html>
### 说明
1. **主进程**:
- 当主窗口接收到来自渲染进程的消息时,会创建一个新窗口。
- 新窗口加载`newWindow.html`文件,并在页面加载完成后,将消息发送到新窗口。
2. **渲染进程(主窗口)**:
- 用户点击按钮时,发送消息到主进程。
3. **新窗口**:
- 新窗口通过`ipcRenderer`监听来自主进程的消息,并在页面中显示收到的消息。
这样,当你在主窗口点击按钮时,会打开一个新窗口,并在新窗口中显示从主窗口发送的消息。
页:
[1]