IPC快速参考.md 2.1 KB

IPC 快速参考(3步)

步骤1:主进程注册(main.js)

位置:electron/main.js 文件中

1. 修改导入(第1行):

// 第1行,原来:const { app, BrowserWindow } = require('electron')
// 改为:
const { app, BrowserWindow, ipcMain } = require('electron')

2. 注册 IPC 函数(第138行之前,app.whenReady() 之前):

// 在第138行(app.whenReady())之前添加,例如第137行:
ipcMain.handle('函数名', async (event, 参数) => {
  return '返回值'
})

// 第138行(保持不变):
app.whenReady().then(() => {
  createWindow()
  // ... 其他代码
})

具体位置示例:

  • 导入修改:第1行
  • IPC 函数注册:第137行(在 app.whenReady() 之前)

推荐位置: 放在 app.whenReady() 之前,这样应用启动时就能使用。

步骤2:preload 暴露(preload.js)

位置: 创建新文件 electron/preload.js,内容如下:

const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('electronAPI', {
  函数名: (参数) => ipcRenderer.invoke('函数名', 参数)
})

然后在 main.jscreateWindow() 函数中添加(第115行之后):

// 第108行:async function createWindow() {
// 第113-116行:webPreferences 部分
webPreferences: {
  nodeIntegration: false,
  contextIsolation: true,
  preload: path.join(__dirname, 'preload.js')  // 第116行之后添加这一行
}

具体位置:

  • main.js 第115行 contextIsolation: true 之后
  • 添加 preload: path.join(__dirname, 'preload.js'),

步骤3:前端调用(React)

位置: 在 React 组件文件中(如 src/page/xxx.jsx

// 在组件函数内部使用
function MyComponent() {
  const handleClick = async () => {
    const result = await window.electronAPI.函数名(参数)
    console.log(result)
  }
  
  return <button onClick={handleClick}>点击</button>
}

记住

  • 主进程用 ipcMain.handle
  • preload 用 ipcRenderer.invoke
  • 前端用 window.electronAPI.函数名
  • 都是异步,用 await