@el3um4s/ipc-for-electron
Version:
A package to simplify the communication between renderer and node js in Electron applications
43 lines (42 loc) • 1.51 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const electron_1 = require("electron");
function generateContextBridge(listIPC, apiKey = "ipc") {
const listChannels = [];
listIPC.forEach((el) => {
listChannels.push(el.channels);
});
const listAPI = {};
listChannels.forEach((el) => {
const api = getContextBridge(el);
const name = el.nameAPI;
listAPI[name] = Object.assign({}, api);
});
electron_1.contextBridge.exposeInMainWorld(apiKey, Object.assign({}, listAPI));
}
exports.default = generateContextBridge;
function getContextBridge(obj) {
const { validReceiveChannel } = Object.assign({}, obj);
const validSendChannel = getArrayOfValidSendChannel(obj);
return {
send: (channel, data) => {
// whitelist channels
if (validSendChannel.includes(channel)) {
electron_1.ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
if (validReceiveChannel.includes(channel)) {
// Deliberately strip event as it includes `sender`
electron_1.ipcRenderer.on(channel, (event, ...args) => {
func(...args);
});
}
},
};
}
function getArrayOfValidSendChannel(obj) {
const { validSendChannel } = Object.assign({}, obj);
const result = Object.keys(validSendChannel);
return result;
}