electron中子窗口向父窗口发送消息
electron中子窗口向父窗口发送消息在 Electron 中,子窗口(渲染进程)可以通过进程间通信(IPC)向父窗口(主进程)发送消息。这通常是通过`ipcRenderer`和`ipcMain`模块来实现的。以下是一个简单的示例,展示如何从子窗口向父窗口发送消息。
### 1. 在主进程中创建窗口并设置 IPC 监听
**main.js**
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
function createWindow() {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, 'preload.js') // 使用 preload.js 进行安全通信
}
});
mainWindow.loadFile('index.html');
// 创建子窗口
const childWindow = new BrowserWindow({
width: 400,
height: 300,
parent: mainWindow, // 设置父窗口
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
});
childWindow.loadFile('child.html');
// 监听来自子窗口的消息
ipcMain.on('message-from-child', (event, message) => {
console.log(`Received message from child: ${message}`);
// 可以选择将消息发送回主窗口或处理该消息
mainWindow.webContents.send('message-from-main', `Received: ${message}`);
});
}
app.whenReady().then(createWindow);
### 2. 在子窗口中发送消息
**child.html**
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Child Window</title>
</head>
<body>
<h1>Child Window</h1>
<button id="sendMessage">Send Message to Parent</button>
<script>
const { ipcRenderer } = require('electron');
document.getElementById('sendMessage').addEventListener('click', () => {
ipcRenderer.send('message-from-child', 'Hello from the child window!'); // 发送消息到父窗口
});
</script>
</body>
</html>
### 3. 在主窗口中接收消息
**index.html**
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Main Window</title>
</head>
<body>
<h1>Main Window</h1>
<div id="message"></div>
<script>
const { ipcRenderer } = require('electron');
// 监听来自主进程的消息
ipcRenderer.on('message-from-main', (event, message) => {
document.getElementById('message').innerText = message; // 显示消息
});
</script>
</body>
</html>
### 总结
1. 在主进程( `main.js` )中创建主窗口和子窗口,并使用`ipcMain`监听来自子窗口的消息。
2. 在子窗口( `child.html` )中使用`ipcRenderer`发送消息到主进程。
3. 在主窗口( `index.html` )中监听主进程发送的消息,并显示在页面上。
通过这种方式,你可以轻松地在子窗口和父窗口之间进行消息传递。
页:
[1]