electron/lib/browser/ipc-main-internal-utils.ts

39 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-03-20 20:28:31 +00:00
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal';
type IPCHandler = (event: ElectronInternal.IpcMainInternalEvent, ...args: any[]) => any
export const handleSync = function <T extends IPCHandler> (channel: string, handler: T) {
ipcMainInternal.on(channel, async (event, ...args) => {
try {
2020-03-20 20:28:31 +00:00
event.returnValue = [null, await handler(event, ...args)];
} catch (error) {
2020-03-20 20:28:31 +00:00
event.returnValue = [error];
}
2020-03-20 20:28:31 +00:00
});
};
2020-03-20 20:28:31 +00:00
let nextId = 0;
export function invokeInWebContents<T> (sender: Electron.WebContents, command: string, ...args: any[]) {
return new Promise<T>((resolve, reject) => {
2020-03-20 20:28:31 +00:00
const requestId = ++nextId;
const channel = `${command}_RESPONSE_${requestId}`;
ipcMainInternal.on(channel, function handler (event, error: Error, result: any) {
if (event.sender !== sender) {
2020-03-20 20:28:31 +00:00
console.error(`Reply to ${command} sent by unexpected WebContents (${event.sender.id})`);
return;
}
2020-03-20 20:28:31 +00:00
ipcMainInternal.removeListener(channel, handler);
if (error) {
2020-03-20 20:28:31 +00:00
reject(error);
} else {
2020-03-20 20:28:31 +00:00
resolve(result);
}
2020-03-20 20:28:31 +00:00
});
sender._sendInternal(command, requestId, ...args);
2020-03-20 20:28:31 +00:00
});
}