|
1 | 1 | import { ipcRenderer, contextBridge } from 'electron'
|
2 | 2 |
|
3 | 3 | // --------- 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 | + }, |
12 | 21 |
|
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 | +}) |
24 | 25 |
|
25 | 26 | // --------- Preload scripts loading ---------
|
26 | 27 | function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {
|
|
0 commit comments