10000 feat: better `ipcRenderer` api expose · coder-long/electron-vite-react@2a85faf · GitHub
[go: up one dir, main page]

Skip to content

Commit 2a85faf

Browse files
committed
feat: better ipcRenderer api expose
1 parent 3e58a0b commit 2a85faf

File tree

1 file changed

+20
-19
lines changed

1 file changed

+20
-19
lines changed

electron/preload/index.ts

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,27 @@
11
import { ipcRenderer, contextBridge } from 'electron'
22

33
// --------- Expose some API to the Renderer process ---------
4-
contextBridge.exposeInMainWorld('ipcRenderer', withPrototype(ipcRenderer))
5-
6-
// `exposeInMainWorld` can't detect attributes and methods of `prototype`, manually patching it.
7-
function withPrototype(obj: Record<string, any>) {
8-
const protos = Object.getPrototypeOf(obj)
9-
10-
for (const [key, value] of Object.entries(protos)) {
11-
if (Object.prototype.hasOwnProperty.call(obj, key)) continue
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)
16+
},
17+
invoke(...args: Parameters<typeof ipcRenderer.invoke>) {
18+
const [channel, ...omit] = args
19+
ipcRenderer.invoke(channel, ...omit)
20+
},
1221

13-
if (typeof value === 'function') {
14-
// Some native APIs, like `NodeJS.EventEmitter['on']`, don't work in the Renderer process. Wrapping them into a function.
15-
obj[key] = function (...args: any) {
16-
return value.call(obj, ...args)
17-
}
18-
} else {
19-
obj[key] = value
20-
}
21-
}
22-
return obj
23-
}
22+
// You can expose other APTs you need here.
23+
// ...
24+
})
2425

2526
// --------- Preload scripts loading ---------
2627
function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {

0 commit comments

Comments
 (0)
0