一、Electron的基本架构
Electron应用由两个主要进程组成:
+-------------------+ +-------------------+
| 主进程(Main) | | 渲染进程(Renderer)|
|-------------------| |-------------------|
| - 管理应用生命周期 | | - 显示网页内容 |
| - 访问Node.js API |<----->| - 受限环境 |
| - 创建浏览器窗口 | IPC | - 通过IPC与主进程 |
+-------------------+ +-------------------+
二、IPC通信的基本流程
当渲染进程需要访问系统资源时,完整的IPC通信流程如下:
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 用户操作 │ │ 渲染进程 │ │ 主进程 │
└──────┬──────┘ └──────┬──────┘ └──────┬──────┘
│ │ │
│ 点击"读取文件"按钮 │ │
│─────────────────>│ │
│ │ │
│ │ ipcRenderer.invoke│
│ │────("read-file")──>│
│ │ │
│ │ │ 读取文件系统
│ │ │───────┐
│ │ │<──────┘
│ │ │
│ │ 返回文件内容 │
│ │<───(fileData)─────│
│ │ │
│ 更新DOM显示内容 │ │
│<─────────────────│ │
│ │ │
三、代码实现详解
1. 主进程设置IPC监听器
// main.ts
ipcMain.handle('read-file', async (event, filePath) => {
try {
// 读取文件内容
const data = await fs.promises.readFile(filePath, 'utf-8');
return { success: true, data };
} catch (error) {
return { success: false, error: error.message };
}
});
2. 渲染进程发起IPC请求
// renderer.ts
const readFile = async () => {
const result = await ipcRenderer.invoke('read-file', '/path/to/file.txt');
if (result.success) {
document.getElementById('content').innerText = result.data;
} else {
console.error('读取文件失败:', result.error);
}
};
document.getElementById('readBtn').addEventListener('click', readFile);
四、完整通信时序图
渲染进程 主进程
│ │
│ 1. click "Read File" │
│────────────────────────>│
│ │
│ 2. invoke('read-file') │
│────────────────────────>│
│ │
│ │ 3. fs.readFile()
│ │─────────────────┐
│ │<────────────────┘
│ │
│ 4. return fileData │
│<────────────────────────│
│ │
│ 5. update DOM │
│────────────────────────>│
│ │
五、常见IPC模式
1. 渲染进程 → 主进程 (单向)
渲染进程 主进程
│ │
│ send() │
│──────────>│
│ │
2. 渲染进程 ↔ 主进程 (双向)
渲染进程 主进程
│ │
│ invoke() │
│──────────>│
│ │
│ response │
│<──────────│
│ │
3. 主进程 → 渲染进程 (推送)
主进程 渲染进程
│ │
│ send() │
│──────────>│
│ │
六、安全注意事项
+----------------------+ +-----------------------+
| 不安全做法 | | 安全做法 |
|----------------------| |-----------------------|
| nodeIntegration: true| | contextIsolation: true|
| contextIsolation:false| | 使用preload脚本 |
| 直接暴露所有Node API | | 有限暴露必要API |
+----------------------+ +-----------------------+
通过以上ASCII流程图和代码示例,相信您已经对Electron的IPC机制有了更直观的理解。实际开发中,建议结合具体业务需求选择合适的IPC通信模式。
评论区