refactor: replace ipcRendererUtils.invoke() with ipcRendererInternal.invoke() (#19574)
This commit is contained in:
parent
698120daf0
commit
81e9dab52f
29 changed files with 195 additions and 164 deletions
|
@ -1,38 +1,6 @@
|
|||
import { EventEmitter } from 'events'
|
||||
import { IpcMainInvokeEvent } from 'electron'
|
||||
import { IpcMainImpl } from '@electron/internal/browser/ipc-main-impl'
|
||||
|
||||
class IpcMain extends EventEmitter {
|
||||
private _invokeHandlers: Map<string, (e: IpcMainInvokeEvent, ...args: any[]) => void> = new Map();
|
||||
|
||||
handle: Electron.IpcMain['handle'] = (method, fn) => {
|
||||
if (this._invokeHandlers.has(method)) {
|
||||
throw new Error(`Attempted to register a second handler for '${method}'`)
|
||||
}
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`Expected handler to be a function, but found type '${typeof fn}'`)
|
||||
}
|
||||
this._invokeHandlers.set(method, async (e, ...args) => {
|
||||
try {
|
||||
(e as any)._reply(await Promise.resolve(fn(e, ...args)))
|
||||
} catch (err) {
|
||||
(e as any)._throw(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
handleOnce: Electron.IpcMain['handleOnce'] = (method, fn) => {
|
||||
this.handle(method, (e, ...args) => {
|
||||
this.removeHandler(method)
|
||||
return fn(e, ...args)
|
||||
})
|
||||
}
|
||||
|
||||
removeHandler (method: string) {
|
||||
this._invokeHandlers.delete(method)
|
||||
}
|
||||
}
|
||||
|
||||
const ipcMain = new IpcMain()
|
||||
const ipcMain = new IpcMainImpl()
|
||||
|
||||
// Do not throw exception when channel name is "error".
|
||||
ipcMain.on('error', () => {})
|
||||
|
|
|
@ -327,14 +327,15 @@ WebContents.prototype._init = function () {
|
|||
}
|
||||
})
|
||||
|
||||
this.on('-ipc-invoke', function (event, channel, args) {
|
||||
this.on('-ipc-invoke', function (event, internal, channel, args) {
|
||||
event._reply = (result) => event.sendReply({ result })
|
||||
event._throw = (error) => {
|
||||
console.error(`Error occurred in handler for '${channel}':`, error)
|
||||
event.sendReply({ error: error.toString() })
|
||||
}
|
||||
if (ipcMain._invokeHandlers.has(channel)) {
|
||||
ipcMain._invokeHandlers.get(channel)(event, ...args)
|
||||
const target = internal ? ipcMainInternal : ipcMain
|
||||
if (target._invokeHandlers.has(channel)) {
|
||||
target._invokeHandlers.get(channel)(event, ...args)
|
||||
} else {
|
||||
event._throw(`No handler registered for '${channel}'`)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue