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)
}
相关推荐
踩着两条虫21 分钟前
VTJ.PRO 核心架构全公开!从设计稿到代码,揭秘AI智能体如何“听懂人话”
前端·vue.js·ai编程
jzlhll1231 小时前
kotlin Flow first() last()总结
开发语言·前端·kotlin
用头发抵命2 小时前
Vue 3 中优雅地集成 Video.js 播放器:从组件封装到功能定制
开发语言·javascript·ecmascript
蓝冰凌2 小时前
Vue 3 中 defineExpose 的行为【defineExpose暴露ref变量】详解:自动解包、响应性与实际使用
前端·javascript·vue.js
奔跑的呱呱牛2 小时前
generate-route-vue基于文件系统的 Vue Router 动态路由生成工具
前端·javascript·vue.js
sp42a3 小时前
在 NativeScript-Vue 中实现流畅的共享元素转场动画
vue.js·nativescript·app 开发
柳杉3 小时前
从动漫水面到赛博飞船:这位开发者的Three.js作品太惊艳了
前端·javascript·数据可视化
Greg_Zhong3 小时前
前端基础知识实践总结,每日更新一点...
前端·前端基础·每日学习归类
We་ct3 小时前
LeetCode 148. 排序链表:归并排序详解
前端·数据结构·算法·leetcode·链表·typescript·排序算法