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

45 lines
1.3 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: Electron.IpcMainInvokeEvent, ...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.WebContentsInternal, sendToAll: boolean, 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: Electron.SerializedError, 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
});
if (sendToAll) {
2020-03-20 20:28:31 +00:00
sender._sendInternalToAll(command, requestId, ...args);
} else {
2020-03-20 20:28:31 +00:00
sender._sendInternal(command, requestId, ...args);
}
2020-03-20 20:28:31 +00:00
});
}