位置: 在 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()
// ... 其他代码
})
具体位置示例:
app.whenReady() 之前)推荐位置: 放在 app.whenReady() 之前,这样应用启动时就能使用。
位置: 创建新文件 electron/preload.js,内容如下:
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
函数名: (参数) => ipcRenderer.invoke('函数名', 参数)
})
然后在 main.js 的 createWindow() 函数中添加(第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'),位置: 在 React 组件文件中(如 src/page/xxx.jsx)
// 在组件函数内部使用
function MyComponent() {
const handleClick = async () => {
const result = await window.electronAPI.函数名(参数)
console.log(result)
}
return <button onClick={handleClick}>点击</button>
}
ipcMain.handleipcRenderer.invokewindow.electronAPI.函数名await