I have been struggling with Inter-Process Communication (IPC) for 5 days. (Also dealing with COVID too)
Finally, I have understood how to use methods such as 'ipcRenderer.invoke' and 'ipcMain.handle' a bit.
However, there are still many things to learn.
What I did
- Googling about ipcMain.on and event.reply
I couldn't understand event.reply even after using chat-GPT. I referred to the following article and used .invoke
and .handle
instead.
- Copying and pasting tutorial code and modifying it
And here is what I made:
// main.js console.log("Main process working"); console.log("main.js"); "use strict" const { app, BrowserWindow, ipcMain, dialog} = require('electron'); const path = require('path'); const url = require('url'); let win; function createWindow() { const mainWindow = new BrowserWindow({ width: 400, height: 300, title: 'IPC App', webPreferences: { nodeIntegration: true, contextIsolation: false, } }); ipcMain.handle('open-dialog', async (_e, _arg) => { return "hogehoge" // .showOpenDialog(mainWindow, { // properties: ['openFile'], // }) // .then((result) => { // if (result.cancelled) return "Cancelled hoge"; // return "hoge"; // }); }); mainWindow.loadFile('index.html'); }; app.once('ready', () => { createWindow(); }); app.once('window-all-closed', () => app.quit());
<!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="Content-Security-policy" content="default-src 'self'" /> <meta name="viewport" content="width=device-width, inicial-scale=1.0" /> <title>IPC App</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h2>Input something</h2> URL: <input id="URL"/> <button id="errorBtn">Open</button> <p id="text"></p> <script src="index.js"></script> </body> </html>
const {ipcRenderer} = require("electron"); const Button = document.getElementById("Button"); const text = document.getElementById("text"); errorBtn.addEventListener('click', async () => { console.log("index.js"); text.textContent = await ipcRenderer.invoke('open-dialog'); });
I will try to use the packaging function tomorrow.
Top comments (0)