Skip to content

Commit

Permalink
feat: upgrade to electron@29 #467
Browse files Browse the repository at this point in the history
  • Loading branch information
caoxiemeihao committed Mar 11, 2024
1 parent 8a73559 commit a9952f1
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 23 deletions.
27 changes: 8 additions & 19 deletions electron/preload/index.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,15 @@
import { ipcRenderer, contextBridge } from 'electron'

// --------- Expose some API to the Renderer process ---------
contextBridge.exposeInMainWorld('ipcRenderer', withPrototype(ipcRenderer))
contextBridge.exposeInMainWorld('app', {
onEvent(cb) {
const channel = 'main-process-message'
const channel2 = 'other-ipc-channel'

// `exposeInMainWorld` can't detect attributes and methods of `prototype`, manually patching 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 APIs, like `NodeJS.EventEmitter['on']`, don't work in the Renderer process. Wrapping them into a function.
obj[key] = function (...args: any) {
return value.call(obj, ...args)
}
} else {
obj[key] = value
}
}
return obj
}
ipcRenderer.on(channel, (_e, ...args) => cb(channel, ...args))
ipcRenderer.on(channel2, (_e, ...args) => cb(channel2, ...args))
},
})

// --------- Preload scripts loading ---------
function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {
Expand Down
4 changes: 2 additions & 2 deletions src/demos/ipc.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@

window.ipcRenderer.on('main-process-message', (_event, ...args) => {
console.log('[Receive Main-process message]:', ...args)
window.app.onEvent((channel, ...args) => {
console.log(channel, ...args)
})
6 changes: 4 additions & 2 deletions src/vite-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ declare module '*.vue' {
}

interface Window {
// expose in the `electron/preload/index.ts`
ipcRenderer: import('electron').IpcRenderer
app: {
// Expose in the `electron/preload/index.ts`
onEvent: (cb: (channel: string, ...args: any[]) => void) => void
}
}

0 comments on commit a9952f1

Please sign in to comment.