@electron-toolkit/typed-ipc
Version:
Type-safe Electron IPC, best practices in TypeScript.
49 lines (46 loc) • 1.15 kB
JavaScript
import { ipcMain } from 'electron';
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Typed listener for Electron `ipcMain`.
*/
class IpcListener {
constructor() {
this.listeners = [];
this.handlers = [];
}
/**
* Listen to `channel`.
*/
on(channel, listener) {
this.listeners.push(channel);
ipcMain.on(channel, listener);
}
/**
* Handle a renderer invoke request.
*/
handle(channel, listener) {
this.handlers.push(channel);
ipcMain.handle(channel, listener);
}
/**
* Dispose all listeners and handlers.
*/
dispose() {
this.listeners.forEach(c => ipcMain.removeAllListeners(c));
this.listeners = [];
this.handlers.forEach(c => ipcMain.removeHandler(c));
this.handlers = [];
}
}
/**
* Typed emitter for sending an asynchronous message to the renderer process.
*/
class IpcEmitter {
/**
* Send an asynchronous message to the renderer process.
*/
send(sender, channel, ...args) {
sender.send(channel, ...args);
}
}
export { IpcEmitter, IpcListener };