I am trying to learn electron, but I'm struggling to understand this basic functionality of IPC. Already tried from documentation or tutorials but everytime they overcomplicate with complex examples or using other libaries like svelte, typescript etc. Also I don't want to show in console, I want to display directly in HTML page. I know these are basics, but any help is appreciated. So far I understood that I need:
main.js
const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path");
app.whenReady().then(main);
let window;
async function main() {
window = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
preload: path.join(__dirname + "./preload.js")
},
})
window.on("ready-to-show", window.show);
window.loadFile(path.join(__dirname, "./index.html"));
}
ipcMain.on("GetMyVar", (event, args) => {
*???*
})
preload.js
const { ipcRenderer, contextBridge } = require("electron");
const API = {
window: {
GetMyVar: () => ipcRenderer.send("GetMyVar", MyVar) *???*
},
}
contextBridge.exposeInMainWorld("app", API);
renderer.js
const MyVar = "JUSTSHOWUP!";
index.html
<html>
<body>
<h1 id='MyVar'>???</h1>
</body>
</html>
Thank you!
Electron Inter-Process Communication is a difficult subject to grasp without easy to understand examples.
Your
preload.jsscript can be written in a number of different ways. In the below code example, I have included two ways to do this.preload-1.jsuses a simplified, easy to understand direct implementation method. That said, for ease of maintainability and debugging, as your Electron application grows, you will want to split yourpreload.jsscript up into smaller individualpreloadscripts. Bearing in mind that you can only load onepreloadscript per window instance, you may have a need to repeat code betweenpreloadscripts.preload-2.jsuses a more flexible white listed channel naming system where you only need to load the onepreloadscript across all created windows. As a result, yourpreloadscript only performs a single function, to communicate between your main process and render process(es). Implementation of the sent and received channel names are kept within your specific code domains.main.js(main process)No matter which type of
preloadscript you use, implementation will be the same within yourmain.jsfile.preload-1.js(main process)preload-2.js(main process)At the end of this
preload.jsscript, I have included a section on how to use it within your main process and render process(es).index.html(render process)To test which form of
preload.jsscript you prefer, just comment out one whilst uncommenting the other.