refactor: add ipcMainUtils.invokeInWebContents / ipcRendererUtils.handle helpers (#17313)

This commit is contained in:
Milan Burda 2019-03-13 20:03:17 +01:00 committed by Shelley Vohr
parent df7dc9396e
commit faabd0cc8b
5 changed files with 44 additions and 5 deletions

View file

@ -9,6 +9,7 @@ const { app, ipcMain, session, deprecate } = electron
const NavigationController = require('@electron/internal/browser/navigation-controller')
const { ipcMainInternal } = require('@electron/internal/browser/ipc-main-internal')
const ipcMainUtils = require('@electron/internal/browser/ipc-main-internal-utils')
const errorUtils = require('@electron/internal/common/error-utils')
// session is not used here, the purpose is to make sure session is initalized
@ -193,7 +194,7 @@ const asyncWebFrameMethods = function (requestId, method, callback, ...args) {
for (const method of webFrameMethods) {
WebContents.prototype[method] = function (...args) {
this._sendInternal('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', method, args)
ipcMainUtils.invokeInWebContents(this, 'ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', method, ...args)
}
}

View file

@ -1,7 +1,7 @@
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal'
import * as errorUtils from '@electron/internal/common/error-utils'
type IPCHandler = (...args: any[]) => any
type IPCHandler = (event: ElectronInternal.IpcMainInternalEvent, ...args: any[]) => any
const callHandler = async function (handler: IPCHandler, event: ElectronInternal.IpcMainInternalEvent, args: any[], reply: (args: any[]) => void) {
try {
@ -23,3 +23,21 @@ export const handle = function <T extends IPCHandler> (channel: string, handler:
})
})
}
let nextId = 0
export function invokeInWebContents<T> (sender: Electron.WebContentsInternal, command: string, ...args: any[]) {
return new Promise<T>((resolve, reject) => {
const requestId = ++nextId
ipcMainInternal.once(`${command}_RESPONSE_${requestId}`, (
_event, error: Electron.SerializedError, result: any
) => {
if (error) {
reject(errorUtils.deserialize(error))
} else {
resolve(result)
}
})
sender._sendInternal(command, requestId, ...args)
})
}