数据传递(旧)
渲染进程发数据到主进程
// 按钮事件
const handleWebRootPathClick = () => {ipcRenderer.send('open_dir')
}// main.ts中接收
ipcMain.on('open_dir', () => {console.log('recv ok')
})
主进程发数据到渲染进程
// main.ts中发送数据
win.webContents.send('load', {message: "主进程执行了,这是结果"});// 组件中接收
ipcRenderer.on('load', (_, message) => {console.log('主线程过来的数据:', message)
})
数据传递(新)
渲染进程到主进程
// preload.js
const menuOpt = {min: () => ipcRenderer.send('window:minimize'),isMaximized: () => ipcRenderer.invoke('get:isMaximized'),maximize: () => ipcRenderer.send('window:maximize'),restore: () => ipcRenderer.send('window:restore'),close: () => ipcRenderer.send('window:close')
}
contextBridge.exposeInMainWorld('electronAPI', {menuOpt,
})// 渲染进程
const { menuOpt } = window.electronAPI
menuOpt.min()// 主进程
const renderFuncInit = () => {ipcMain.on('window:minimize', () => {win.minimize()win.webContents.send('update-counter', '6666')})ipcMain.on('window:maximize', () => {win.maximize()})ipcMain.on('window:restore', () => {win.restore()})ipcMain.on('window:close', () => {win.close()})ipcMain.handle('get:isMaximized', async () => {return win.isMaximized()})
}
// 初始化app(在 Electron 完成初始化时触发),挂载上面创建的 桌面应用程序窗口
app.whenReady().then(() => {renderFuncInit()createWindow()
})
主进程到渲染进程
// preload.js
contextBridge.exposeInMainWorld('electronAPI', {handleCounter: (callback) => ipcRenderer.on('update-counter', callback)
})// 主进程
win.webContents.send('update-counter', '6666')// 渲染进程
const { menuOpt, handleCounter } = window.electronAPI
handleCounter((_event, value) => {console.log(value, _event)
})
双向通讯
// preload.js
const file = {openDir: (dirPath) => ipcRenderer.invoke('file:openDir', dirPath),
}contextBridge.exposeInMainWorld('electronAPI', {file,
})// 主进程
ipcMain.handle('file:openDir', async (_, dirPath = __dirname) => {const { canceled, filePaths } = await dialog.showOpenDialog({defaultPath: dirPath, // 默认盘properties: ['openFile', 'openDirectory']})return {isCanceled: canceled,files: filePaths}
})// 渲染进程
const openDir = async () => {const { isCanceled, files } = await file.openDir()console.log('dddd', isCanceled, files)
}