feat: expose withPrototype

This commit is contained in:
草鞋没号 2021-12-29 09:15:50 +08:00
parent 92841d142a
commit cf3fd496ab

View File

@ -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<IpcRenderer['on']>) {
return ipcRenderer.on(...args)
contextBridge.exposeInMainWorld('ipcRenderer', withPrototype(ipcRenderer))
// `exposeInMainWorld` can not detect `prototype` attribute and methods, manually patch it.
function withPrototype(obj: Record<string, any>) {
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
}