Library for type-safe use of contextBridge in Electron
npm install electron-typescript-ipcLibrary for type-safe use of contextBridge in Electron.
When we implement ipc using contextBridge in TypeScript, we can't know if the method exists (unsafe).
This library is aimed at making it type-safe to use.
Install with npm (or you can use your favorite tool).
``shell`
npm i electron-typescript-ipc
We have a template repository for using this module.
Please see here:
`typescript
import {
contextBridge,
createIpcRenderer,
GetApiType,
} from 'electron-typescript-ipc';
import { Api } from 'path/to/api.ts';
const ipcRenderer = createIpcRenderer
export type Api = GetApiType<
{
getDataFromStore: (str: string) => Promise
},
{
showAlert: (text: string, num: number) => Promise
}
>;
const api: Api = {
invoke: {
getDataFromStore: async (key: string) => {
return await ipcRenderer.invoke('getDataFromStore', key);
},
},
on: {
showAlert: listener => {
ipcRenderer.on('showAlert', listener);
},
},
};
contextBridge.exposeInMainWorld('myAPI', api);
declare global {
interface Window {
myAPI: Api;
}
}
`
`typescript
const createWindow = (): void => {
const mainWindow = ...
mainWindow.on('ready-to-show', () => {
ipcMain.removeHandler
ipcMain.handle
return await store.get(key);
});
setInterval(ipcMain.send
})
}
`
`typescript``
window.myApi.invoke.getDataFromStore('someKey').then(console.log);
window.myApi.on.showAlert((_event, text) => {
alert(text);
});