mirror of
https://github.com/electron-vite/electron-vite-vue
synced 2025-02-26 13:00:09 +08:00
feat: expose withPrototype
This commit is contained in:
parent
92841d142a
commit
cf3fd496ab
@ -14,10 +14,23 @@ domReady().then(() => {
|
|||||||
// --------- Expose some API to Renderer process. ---------
|
// --------- Expose some API to Renderer process. ---------
|
||||||
contextBridge.exposeInMainWorld('fs', fs)
|
contextBridge.exposeInMainWorld('fs', fs)
|
||||||
contextBridge.exposeInMainWorld('removeLoading', removeLoading)
|
contextBridge.exposeInMainWorld('removeLoading', removeLoading)
|
||||||
contextBridge.exposeInMainWorld('ipcRenderer', {
|
contextBridge.exposeInMainWorld('ipcRenderer', withPrototype(ipcRenderer))
|
||||||
...ipcRenderer,
|
|
||||||
// `exposeInMainWorld` will not expose attribute and mothods from the prototype
|
// `exposeInMainWorld` can not detect `prototype` attribute and methods, manually patch it.
|
||||||
on(...args: Parameters<IpcRenderer['on']>) {
|
function withPrototype(obj: Record<string, any>) {
|
||||||
return ipcRenderer.on(...args)
|
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
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user