electron-vite-react/src/preload/index.ts

45 lines
1.1 KiB
TypeScript
Raw Normal View History

2021-11-02 10:19:50 +08:00
import fs from 'fs'
import path from 'path'
import { contextBridge, ipcRenderer } from 'electron'
2021-11-08 19:17:39 +08:00
import { domReady } from './utils'
2021-11-02 10:19:50 +08:00
import { useLoading } from './loading'
const isDev = process.env.NODE_ENV === 'development'
2021-11-02 10:19:50 +08:00
const { appendLoading, removeLoading } = useLoading()
; (async () => {
await domReady()
appendLoading()
})();
// ---------------------------------------------------
contextBridge.exposeInMainWorld('bridge', {
__dirname,
__filename,
fs,
path,
ipcRenderer: withPrototype(ipcRenderer),
2021-11-02 10:19:50 +08:00
removeLoading,
})
// `exposeInMainWorld` can not detect `prototype` attribute and methods, manually patch it.
function withPrototype(obj: Record<string, any>) {
2021-11-26 08:49:02 +08:00
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)
}
2021-11-26 08:49:02 +08:00
} else {
obj[key] = value
}
}
return obj
}