进程间通信(IPC)
学习使用 Electron 的 IPC 模块(如 `ipcMain` 和 `ipcRenderer`)实现主进程与渲染进程之间的安全通信通道
进程间通信(IPC) 是 CoddyKit 上的免费 Electron Desktop App Development 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Electron Desktop App Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Electron Desktop App Development 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What is IPC in Electron?
In Electron, your application runs across two main types of processes: the Main Process and Renderer Processes.
- The Main Process manages the app's lifecycle and interacts with the operating system.
- Renderer Processes (web pages) display your UI and run your web code.
They can't directly access each other's resources or global variables. This is where Inter-Process Communication (IPC) comes in!
Why IPC is Essential
Imagine your Renderer Process needs to:
- Read a file from the user's computer.
- Open a native dialog box.
- Perform a heavy task without freezing the UI.
These actions require access to Node.js modules or the OS, which are restricted to the Main Process for security and stability. IPC provides a safe way for these processes to talk to each other.
IPC Core Modules: ipcMain & ipcRenderer
Electron provides two special modules for IPC:
ipcMain: Used in the Main Process to listen for and send messages.ipcRenderer: Used in Renderer Processes to send messages to the main process and listen for replies.
These modules are the backbone of communication between your Electron app's different parts.
Renderer to Main: One-Way Send
The most common communication is from a Renderer Process to the Main Process. You can send a message using ipcRenderer.send().
This is useful for triggering native actions or requesting data from the main process without needing an immediate reply in the renderer.
Code: Renderer to Main (Client)
Here's how your renderer.js would send a message when a button is clicked. You'd also need an index.html with a button (<button id="myButton">) that loads this script.
const { ipcRenderer } = require('electron');
document.addEventListener('DOMContentLoaded', () => {
const btn = document.getElementById('myButton');
if (btn) {
btn.addEventListener('click', () => {
ipcRenderer.send('channel-name', 'Hello from Renderer!');
console.log('Renderer sent message.');
});
}
});Code: Renderer to Main (Server)
This is the main.js code. It sets up the Electron window and uses ipcMain.on() to listen for messages on the specified 'channel-name'.
Note: nodeIntegration and contextIsolation are simplified here. For secure apps, use preload scripts.
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true, // Simplified for demo
contextIsolation: false // Simplified for demo
}
});
mainWindow.loadFile('index.html');
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
app.whenReady().then(() => {
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// Handle messages from the renderer process
ipcMain.on('channel-name', (event, message) => {
console.log('Main process received:', message);
// Acknowledge or perform an action
});Main to Renderer: One-Way Send
The Main Process can also send messages to a Renderer Process using mainWindow.webContents.send().
This is useful for pushing updates from the main process (e.g., progress updates, data changes) to the UI without the renderer having to request them.
Code: Main to Renderer (Server)
This main.js will send a message to the renderer once the window has finished loading. This time, the ipcMain isn't listening, but sending!
const { app, BrowserWindow } = require('electron');
const path = require('path');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
mainWindow.loadFile('index.html');
// Send a message to the renderer after the window is ready
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.webContents.send('main-channel', 'Update from Main!');
console.log('Main sent message to renderer.');
});
mainWindow.on('closed', () => {
mainWindow = null;
});
}
app.whenReady().then(() => {
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});Code: Main to Renderer (Client)
In your renderer.js, you'll use ipcRenderer.on() to listen for messages coming from the main process. We'll display it in a <div id="messageDisplay">.
const { ipcRenderer } = require('electron');
document.addEventListener('DOMContentLoaded', () => {
const messageDiv = document.getElementById('messageDisplay');
if (messageDiv) {
ipcRenderer.on('main-channel', (event, message) => {
messageDiv.innerText = `Received: ${message}`;
console.log('Renderer received:', message);
});
}
});Request/Reply with Invoke & Handle
For more complex interactions where the Renderer needs a response from the Main Process, Electron offers a request/reply pattern.
ipcRenderer.invoke(channel, ...args): Sends a message from renderer and waits for a response.ipcMain.handle(channel, listener): In the main process, sets up a handler function that processes the request and returns a value (or a Promise that resolves to a value).
This allows for more structured and asynchronous communication.
Quick Check: IPC Methods
Which of the following statements about Electron's IPC modules are TRUE?
Recap: Inter-Process Communication
Great job! You've learned the fundamentals of Electron's Inter-Process Communication.
- IPC is vital for Main and Renderer Processes to safely interact.
ipcMainandipcRendererare the core modules.- One-way communication uses
ipcRenderer.send()(Renderer to Main) andwebContents.send()(Main to Renderer). - For request/reply patterns,
ipcRenderer.invoke()andipcMain.handle()provide a robust solution.
You're now ready to build more interactive and powerful Electron applications!
常见问题解答
「进程间通信(IPC)」课时是免费的吗?
是的 — 「进程间通信(IPC)」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Electron Desktop App Development 课程的其余内容,请升级到 CoddyKit PRO。 Electron Desktop App Development 课程共包含 4 节课。
「进程间通信(IPC)」这节课中我会学到什么?
学习使用 Electron 的 IPC 模块(如 `ipcMain` 和 `ipcRenderer`)实现主进程与渲染进程之间的安全通信通道 你通过在浏览器中直接运行的动手代码来练习 Electron Desktop App Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Electron Desktop App Development 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Electron Desktop App Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「进程间通信(IPC)」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Electron Desktop App Development 课中编写并运行代码吗?
能。每节 Electron Desktop App Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 主进程与渲染进程
- 进程间通信(IPC)
- 打包您的 Electron 应用
- 管理多个窗口