2023最新electron 进程间通讯的几种方法

数据传递(旧)

渲染进程发数据到主进程

复制代码
// 按钮事件
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)
}
相关推荐
haogexiaole1 小时前
vue知识点总结
前端·javascript·vue.js
哆啦A梦15883 小时前
[前台小程序] 01 项目初始化
前端·vue.js·uni-app
智码看视界4 小时前
老梁聊全栈系列:(阶段一)架构思维与全局观
java·javascript·架构
小周同学@5 小时前
谈谈对this的理解
开发语言·前端·javascript
Wiktok6 小时前
Pyside6加载本地html文件并实现与Javascript进行通信
前端·javascript·html·pyside6
一只小风华~6 小时前
Vue:条件渲染 (Conditional Rendering)
前端·javascript·vue.js·typescript·前端框架
柯南二号6 小时前
【大前端】前端生成二维码
前端·二维码
程序员码歌6 小时前
明年35岁了,如何破局?说说心里话
android·前端·后端
博客zhu虎康7 小时前
React Hooks 报错?一招解决useState问题
前端·javascript·react.js