Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mefengl/simple-electron-ipc
https://github.com/mefengl/simple-electron-ipc
Last synced: 10 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/mefengl/simple-electron-ipc
- Owner: mefengl
- License: mit
- Created: 2023-04-25T17:22:13.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2023-04-25T17:27:03.000Z (over 1 year ago)
- Last Synced: 2024-10-30T10:15:42.154Z (about 2 months ago)
- Size: 2.93 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# simple-electron-ipc
```js
// https://stackoverflow.com/a/71495848/14435416
// preload.js// Import the necessary Electron components.
const contextBridge = require('electron').contextBridge;
const ipcRenderer = require('electron').ipcRenderer;// White-listed channels.
const ipc = {
'render': {
// From render to main.
'send': [
'message:fromRender'
],
// From main to render.
'receive': [
'message:toRender'
],
// From render to main and back again.
'sendReceive': []
}
};// Exposed protected methods in the render process.
contextBridge.exposeInMainWorld(
// Allowed 'ipcRenderer' methods.
'ipcRender', {
// From render to main.
send: (channel, args) => {
let validChannels = ipc.render.send;
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, args);
}
},
// From main to render.
receive: (channel, listener) => {
let validChannels = ipc.render.receive;
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`.
ipcRenderer.on(channel, (event, ...args) => listener(...args));
}
},
// From render to main and back again.
invoke: (channel, args) => {
let validChannels = ipc.render.sendReceive;
if (validChannels.includes(channel)) {
return ipcRenderer.invoke(channel, args);
}
}
}
);
```above code can't take advantage of auto-completion, so need to further improve it.
like below(not finished yet)
```js
const { contextBridge, ipcRenderer } = require('electron')const validChannels = {
// From render to main.
'send': [],
// From main to render.
'receive': [],
// From render to main and back again.
'sendReceive': []
};const easy_expose = (functionNames) => {
const exposedFunctions = {};
functionNames.forEach(functionName => {
const trigger_id = functionName.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
exposedFunctions[functionName] = (...args) => ipcRenderer.send(trigger_id, ...args);
});contextBridge.exposeInMainWorld('electronAPI', exposedFunctions);
};easy_expose(validChannels.send);
```