diff --git a/src/preload/index.ts b/src/preload/index.ts index 0121e9b..ec4636b 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -20,6 +20,24 @@ contextBridge.exposeInMainWorld('bridge', { __filename, fs, path, - ipcRenderer, + ipcRenderer: withPrototype(ipcRenderer), removeLoading, }) + +// `exposeInMainWorld` can not detect `prototype` attribute and methods, manually patch it. +function withPrototype(obj: Record) { + const protos = Object.entries(Object.getPrototypeOf(obj)) + for (const [key, value] of protos) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (typeof value === 'function') { + // Some native API not work Renderer-process, like `NodeJS.EventEmitter['on']`. Wrap a function patch it. + obj[key] = function (...args: any) { + return value.call(obj, ...args) + } + } else { + Object.assign(obj, { [key]: value }) + } + } + } + return obj +}