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