1.2.1 • Published 5 years ago
@kalphax/core v1.2.1
Kalphax
Project Setup
Add the following code to your Electron project.
declarations.d.ts
import { Bridge } from '@kalphax/core';
declare global {
interface Window {
[x: string]: <T>() => Promise<T>;
}
}main.ts (Electron main process)
ipcMain.on('to.myFunction', (event, value: string) => {
// ...
return `You provided value: ${value}`;
});preload.ts (Electron preloader)
import { contextBridge } from 'electron';
contextBridge.exposeInMainWorld('api', {
myFunction: async (value: string): Promise<string> => {
// Spawn a bridge with the following channels
const myBridge = new Bridge({
channels: {
senders: ['to.myFunction'],
receivers: ['from.myFunction']
}
});
// Give the signal to ipcMain to run myFunction
myBridge.send<string>('to.myFunction', value);
// Wait for ipcMain to finish its process and return a value
const result = await myBridge.receive<string>('from.myFunction');
// Unsubscribe all listeners
myBridge.dispose();
return result;
}
});Accessing a bridge
Accessing a property from your bridge is easy. Simply call window.api.<property>. For instance, if your context bridge looks like the one in the example above, you would call window.api.myFunction.send and window.api.myFunction.receive.
Here are some examples on how to utilize the IPC bridge.
Vanilla
<body>
<div id="myFunctionResult"></div>
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function() {
window.api.myFunction().then(data => {
document.getElementById('myFunctionResult').innerText = data;
});
});
</script>
</body>React
import React, { useState } from 'react';
const MyComponent = () => {
const [loading, setLoading] = useState<boolean>(true);
const [runningMyFunction, setRunningMyFunction] = useState<boolean>(false);
const [errorMyFunction, setErrorMyFunction] = useState<boolean>(false);
const [myFunctionResult, setMyFunctionResult] = useState<string>();
if (loading && !fetchingUniqueId) {
setFetchingUniqueId(true);
window.api.myFunction('from.myFunction')
.then((data: string) => setMyFunctionResult(data))
.catch(() => setErrorMyFunction(true))
.finally(() => setRunningMyFunction(false));
}
if (loading && myFunctionResult !== undefined || errorMyFunction) {
setLoading(false);
}
return (
<div>{myFunctionResult}</div>
)
}