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)
}
相关推荐
我不吃饼干9 天前
鸽了六年的某大厂面试题:你会手写一个模板引擎吗?
前端·javascript·面试
涵信9 天前
第一节 布局与盒模型-Flex与Grid布局对比
前端·css
我不吃饼干9 天前
鸽了六年的某大厂面试题:手写 Vue 模板编译(解析篇)
前端·javascript·面试
前端fighter9 天前
为什么需要dependencies 与 devDependencies
前端·javascript·面试
满楼、9 天前
el-cascader 设置可以手动输入也可以下拉选择
javascript·vue.js·elementui
veminhe9 天前
HTML5 浏览器支持
前端·html·html5
前端fighter9 天前
Vuex 与 Pinia:全面解析现代 Vue 状态管理的进化之路
前端·vue.js·面试
嘉琪0019 天前
2025——js 面试题
开发语言·javascript·ecmascript
snow@li9 天前
vue3-ts-qrcode :安装及使用记录 / 配置项 / 效果展示
前端·javascript·vue.js
海天胜景9 天前
vue3 el-table 根据字段值 改变整行字体颜色
javascript·vue.js·elementui