[electron-ipc-demo] 基于 Proxy 实现的 ipc 演示

Published on
39

实现方式

  1. 首先需要在主进程注册 ipc 事件

ipcMain.handle('ipc', async (event, { action, args }) => {
  // 通过 cls-hooked 无感在调用链中传递 event
  return ipcHook.runAndReturn(() => {
    ipcHook.set('event', event)
    return ipc[action](...args)
  })
})

以上使用 cls-hooked 在调用链中传递 event,避免需要显式传递 event。

  1. 在入口文件中初始化 ipc

ipc.init()
  1. 在渲染进程中使用 proxy 调用 ipc

// 直接通过 import 获得 ipc 类型
export const ipc: import('../../main/ipc').Ipc = new Proxy(
  {},
  {
    get(_, action: string) {
      return async (...args: any[]) => {
        return await window.electron.ipcRenderer.invoke('ipc', {
          action,
          args
        })
      }
    }
  }
) as any

以上。

https://github.com/lblblong/electron-ipc-demo?tab=readme-ov-file

下载链接:https://download.jiang.in/s/mOsK?password=bsxu0h


Prev Post [wechat-need-web] 让微信网页版可用
Next Post 调整Cursor工具栏为竖排