双向IPC的一个常见应用:从渲染器进程代码调用主进程模块并等待结果
【ipcRenderer.invoke】《==============》【ipcMain.handle()】

main.js
| const { app, BrowserWindow, ipcMain, dialog } = require('electron/main') |
| const path = require('node:path') |
| |
| async function handleFileOpen () { |
| const { canceled, filePaths } = await dialog.showOpenDialog() |
| if (!canceled) { |
| return filePaths[0] |
| } |
| } |
| |
| function createWindow () { |
| const mainWindow = new BrowserWindow({ |
| webPreferences: { |
| preload: path.join(__dirname, 'preload.js') |
| } |
| }) |
| mainWindow.loadFile('index.html') |
| } |
| |
| app.whenReady().then(() => { |
| |
| |
| |
| |
| |
| |
| ipcMain.handle('dialog:openFile', handleFileOpen) |
| createWindow() |
| app.on('activate', function () { |
| if (BrowserWindow.getAllWindows().length === 0) createWindow() |
| }) |
| }) |
| |
| app.on('window-all-closed', function () { |
| if (process.platform !== 'darwin') app.quit() |
| }) |
| |
preload.js
| const { contextBridge, ipcRenderer } = require('electron/renderer') |
| |
| |
| |
| contextBridge.exposeInMainWorld('electronAPI', { |
| |
| openFile: () => ipcRenderer.invoke('dialog:openFile') |
| }) |
| |
renderer.js
| const btn = document.getElementById('btn') |
| const filePathElement = document.getElementById('filePath') |
| |
| btn.addEventListener('click', async () => { |
| |
| const filePath = await window.electronAPI.openFile() |
| filePathElement.innerText = filePath |
| }) |
index.html
| <!DOCTYPE html> |
| <html> |
| <head> |
| <meta charset="UTF-8"> |
| |
| <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> |
| <title>Dialog</title> |
| </head> |
| <body> |
| // 构建渲染器进程UI |
| <button type="button" id="btn">Open a File</button> |
| File path: <strong id="filePath"></strong> |
| <script src='./renderer.js'></script> |
| </body> |
| </html> |
| |
使用ipcRenderer.sendSync API向主进程发送消息并同步等待响应
| * main.js(Main Process) |
| |
| ipcMain.on('synchronous-message', (event, arg) => { |
| console.log(arg) |
| event.returnValue = 'pong' |
| }) |
| |
| * preload.js(Preload Script) |
| const { ipcRenderer } = require('electron') |
| const result = ipcRenderer.sendSync('synchronous-message', 'ping') |
| console.log(result) |
| |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2020-11-04 Linux下的Tomcat安装
2020-11-04 Linux下的Java安装
2020-11-04 Linux下的MySQL安装+相关配置