Skip to content

Commit

Permalink
feat: better ipcRenderer expose
Browse files Browse the repository at this point in the history
  • Loading branch information
caoxiemeihao committed Mar 11, 2024
1 parent a9952f1 commit 0ea6832
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 13 deletions.
22 changes: 15 additions & 7 deletions electron/preload/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
import { ipcRenderer, contextBridge } from 'electron'

// --------- Expose some API to the Renderer process ---------
contextBridge.exposeInMainWorld('app', {
onEvent(cb) {
const channel = 'main-process-message'
const channel2 = 'other-ipc-channel'

ipcRenderer.on(channel, (_e, ...args) => cb(channel, ...args))
ipcRenderer.on(channel2, (_e, ...args) => cb(channel2, ...args))
contextBridge.exposeInMainWorld('ipcRenderer', {
on(...args: Parameters<typeof ipcRenderer.on>) {
const [channel, listener] = args
ipcRenderer.on(channel, (event, ...args) => listener(event, ...args))
},
send(...args: Parameters<typeof ipcRenderer.send>) {
const [channel, ...omit] = args
ipcRenderer.send(channel, ...omit)
},
invoke(...args: Parameters<typeof ipcRenderer.invoke>) {
const [channel, ...omit] = args
ipcRenderer.invoke(channel, ...omit)
},

// You can expose other APTs you need here.
// ...
})

// --------- Preload scripts loading ---------
Expand Down
4 changes: 2 additions & 2 deletions src/demos/ipc.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@

window.app.onEvent((channel, ...args) => {
console.log(channel, ...args)
window.ipcRenderer.on('main-process-message', (_event, ...args) => {
console.log('[Receive Main-process message]:', ...args)
})
6 changes: 2 additions & 4 deletions src/vite-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ declare module '*.vue' {
}

interface Window {
app: {
// Expose in the `electron/preload/index.ts`
onEvent: (cb: (channel: string, ...args: any[]) => void) => void
}
// expose in the `electron/preload/index.ts`
ipcRenderer: import('electron').IpcRenderer
}

0 comments on commit 0ea6832

Please sign in to comment.