electron-vite-vue/packages/preload/index.ts

37 lines
1.1 KiB
TypeScript
Raw Normal View History

import fs from 'fs'
import { contextBridge, ipcRenderer } from 'electron'
2021-11-09 08:59:37 +08:00
import { domReady } from './utils'
import { useLoading } from './loading'
2021-09-09 09:37:02 +08:00
const { appendLoading, removeLoading } = useLoading()
;(async () => {
await domReady()
appendLoading()
})()
// --------- Expose some API to the Renderer process. ---------
contextBridge.exposeInMainWorld('fs', fs)
contextBridge.exposeInMainWorld('removeLoading', removeLoading)
2021-12-29 09:15:50 +08:00
contextBridge.exposeInMainWorld('ipcRenderer', withPrototype(ipcRenderer))
// `exposeInMainWorld` can't detect attributes and methods of `prototype`, manually patching it.
2021-12-29 09:15:50 +08:00
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 APIs, like `NodeJS.EventEmitter['on']`, don't work in the Renderer process. Wrapping them into a function.
2021-12-29 09:15:50 +08:00
obj[key] = function (...args: any) {
return value.call(obj, ...args)
}
} else {
obj[key] = value
}
}
2021-12-29 09:15:50 +08:00
return obj
}