electron中的IPC通信及性能进阶技巧_javascript技巧
场景:触发操作无需返回值(如修改窗口标题)。
// 渲染进程(通过预加载脚本暴露API) window.electronAPI.setTitle('新标题'); // 预加载脚本(preload.js) contextBridge.exposeInMainWorld('electronAPI', { setTitle: (title) => ipcRenderer.send('set-title', title) }); // 主进程 ipcMain.on('set-title', (event, title) => { const win = BrowserWindow.fromWebContents(event.sender); win.setTitle(title); });
关键点:使用 ipcRenderer.send
+ ipcMain.on 组合。
场景:需等待主进程返回结果(如读取文件)。推荐方案:invoke/handle(异步Promise风格)
// 渲染进程 const data = await window.electronAPI.readfile('demo.txt'); // 预加载脚本暴露方法 readFile: (path) => ipcRenderer.invoke('read-file', path) // 主进程 ipcMain.handle('read-file', async (event, path) => { return fs.promises.readFile(path, 'utf-8'); });
替代方案:send/reply(传统回调,需手动管理事件)。
场景:实时通知(如系统事件、后台任务完成)。
// 主进程 mainWindow.webContents.send('update-counter', 1); // 渲染进程(通过预加载脚本监听) window.electronAPI.onUpdateCounter((value) => { console.log('计数更新:', value); }); // 预加载脚本注册监听器 onUpdateCounter: (callback) => { ipcRenderer.on('update-counter', (event, value) => callback(value)); }
注意:需通过 webContents 指定目标窗口。
场景:极少需阻塞渲染进程的场景(如小型配置读取)。
// 渲染进程 const reply = ipcRenderer.sendSync('sync-message', 'ping'); // 主进程 ipcMain.on('sync-message', (event, arg) => { event.returnValue = 'pong'; });
风险:阻塞渲染线程导致页面卡顿。
必要性:防止渲染进程直接访问Node.js API,减少攻击面。
// 创建窗口时配置 new BrowserWindow({ webPreferences: { contextIsolation: true, // 默认启用 preload: path.join(__dirname, 'preload.js') } });
预加载脚本作用:唯一安全桥接,仅暴露必要API。
webPreferences: { nodeIntegration: false // 禁止渲染进程直接调用Node模块 }
原则:主进程始终校验传入数据。
ipcMain.handle('write-file', (event, { path, content }) => { if (typeof path !== 'string' || !isValidPath(path)) { throw new Error('非法路径'); } // 执行写入... });
// 主进程发送文件流 const readStream = fs.createReadStream('large-video.mp4'); mainWindow.webContents.send('video-stream', readStream);
批处理示例:合并渲染进程的多次状态更新请求。
useEffect(() => { ipcRenderer.on('event', handler); return () => ipcRenderer.off('event', handler); }, []);
到此这篇关于electron中的IPC通信的文章就介绍到这了,更多相关electron IPC通信内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
本文地址: https://www.earthnavs.com/jishuwz/5658eb750e1c05259a08.html
























