From cf3fd496abee14d0483936ea12720f1f17e5c988 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8D=89=E9=9E=8B=E6=B2=A1=E5=8F=B7?= <308487730@qq.com> Date: Wed, 29 Dec 2021 09:15:50 +0800 Subject: [PATCH] feat: expose withPrototype --- src/preload/index.ts | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/preload/index.ts b/src/preload/index.ts index 3ee8047..cb2242e 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -14,10 +14,23 @@ domReady().then(() => { // --------- Expose some API to Renderer process. --------- contextBridge.exposeInMainWorld('fs', fs) contextBridge.exposeInMainWorld('removeLoading', removeLoading) -contextBridge.exposeInMainWorld('ipcRenderer', { - ...ipcRenderer, - // `exposeInMainWorld` will not expose attribute and mothods from the prototype - on(...args: Parameters) { - return ipcRenderer.on(...args) +contextBridge.exposeInMainWorld('ipcRenderer', withPrototype(ipcRenderer)) + +// `exposeInMainWorld` can not detect `prototype` attribute and methods, manually patch it. +function withPrototype(obj: Record) { + const protos = Object.getPrototypeOf(obj) + + for (const [key, value] of Object.entries(protos)) { + if (Object.prototype.hasOwnProperty.call(obj, key)) continue + + if (typeof value === 'function') { + // Some native API not work in Renderer-process, like `NodeJS.EventEmitter['on']`. Wrap a function patch it. + obj[key] = function (...args: any) { + return value.call(obj, ...args) + } + } else { + obj[key] = value + } } -}) + return obj +}