Skip to content

Commit 11e9c4b

Browse files
committed
feat: better ipcRenderer api expose
1 parent a9952f1 commit 11e9c4b

File tree

3 files changed

+23
-13
lines changed

3 files changed

+23
-13
lines changed

Diff for: electron/preload/index.ts

+19-7
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,26 @@
11
import { ipcRenderer, contextBridge } from 'electron'
22

33
// --------- Expose some API to the Renderer process ---------
4-
contextBridge.exposeInMainWorld('app', {
5-
onEvent(cb) {
6-
const channel = 'main-process-message'
7-
const channel2 = 'other-ipc-channel'
8-
9-
ipcRenderer.on(channel, (_e, ...args) => cb(channel, ...args))
10-
ipcRenderer.on(channel2, (_e, ...args) => cb(channel2, ...args))
4+
contextBridge.exposeInMainWorld('ipcRenderer', {
5+
on(...args: Parameters<typeof ipcRenderer.on>) {
6+
const [channel, listener] = args
7+
ipcRenderer.on(channel, (event, ...args) => listener(event, ...args))
8+
},
9+
off(...args: Parameters<typeof ipcRenderer.off>) {
10+
const [channel, ...omit] = args
11+
ipcRenderer.off(channel, ...omit)
12+
},
13+
send(...args: Parameters<typeof ipcRenderer.send>) {
14+
const [channel, ...omit] = args
15+
ipcRenderer.send(channel, ...omit)
1116
},
17+
invoke(...args: Parameters<typeof ipcRenderer.invoke>) {
18+
const [channel, ...omit] = args
19+
ipcRenderer.invoke(channel, ...omit)
20+
},
21+
22+
// You can expose other APTs you need here.
23+
// ...
1224
})
1325

1426
// --------- Preload scripts loading ---------

Diff for: src/demos/ipc.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11

2-
window.app.onEvent((channel, ...args) => {
3-
console.log(channel, ...args)
2+
window.ipcRenderer.on('main-process-message', (_event, ...args) => {
3+
console.log('[Receive Main-process message]:', ...args)
44
})

Diff for: src/vite-env.d.ts

+2-4
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@ declare module '*.vue' {
77
}
88

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

0 commit comments

Comments
 (0)