如何在 newWindow.html 中向新窗口的渲染进程发送消息
如何在newWindow.html中向新窗口的渲染进程发送消息### 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>
<button id="sendMessageToMain">发送消息到主进程</button>
<script>
const { ipcRenderer } = require('electron');
// 监听来自主进程的消息
ipcRenderer.on('message-from-main', (event, arg) => {
document.getElementById('message').innerText = '收到的消息: ' + arg;
});
// 发送消息到主进程
document.getElementById('sendMessageToMain').addEventListener('click', () => {
ipcRenderer.send('message-from-new-window', '你好,来自新窗口的消息!');
});
</script>
</body>
</html>
### 4. 更新主进程以接收新窗口的消息
在`main.js`中添加以下代码,以便接收来自新窗口的消息:
// 监听来自新窗口的消息
ipcMain.on('message-from-new-window', (event, arg) => {
console.log('Received message from new window:', arg);
});
### 说明
1. **主进程**:
- 监听来自渲染进程的消息,并在接收到消息后创建新窗口。
- 监听来自新窗口的消息并在控制台打印。
2. **主窗口(index.html)**:
- 用户点击按钮时,发送消息到主进程。
3. **新窗口(newWindow.html)**:
- 接收主进程发送的消息并显示在页面上。
- 用户可以通过点击按钮发送消息回主进程。
通过这种方式,你可以在新窗口中接收主进程的消息,并且可以向主进程发送消息。
页:
[1]