From 7f6df58801ac41e7e465c156693ed0f0693eed12 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: Thu, 25 Nov 2021 19:38:26 +0800 Subject: [PATCH] feat: Enhance exposeInMainWorld exposed attribute --- src/preload/index.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) 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 +}