feat: Enhance exposeInMainWorld exposed attribute

This commit is contained in:
草鞋没号 2021-11-25 19:38:26 +08:00
parent d86fa01865
commit 7f6df58801
1 changed files with 19 additions and 1 deletions

View File

@ -20,6 +20,24 @@ contextBridge.exposeInMainWorld('bridge', {
__filename, __filename,
fs, fs,
path, path,
ipcRenderer, ipcRenderer: withPrototype(ipcRenderer),
removeLoading, removeLoading,
}) })
// `exposeInMainWorld` can not detect `prototype` attribute and methods, manually patch it.
function withPrototype(obj: Record<string, any>) {
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
}