Inter-Process Communication
This page describes step by step how to setup IPC between main and renderer processes
Preload Scripts
Preload Scripts contain code that is executed in the renderer process. These scripts run in renderer context but have more privileges by having access to Node.js APIs, allowing them to have access to the OS functions.
Lets start by adding a Preload Script to our application
1
2
Import Preload Script in main
import { BrowserWindow, app, ipcMain } from "electron";
import path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
let win;
const createWindow = () => {
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, "preload.mjs"),
contextIsolation: true,
nodeIntegration: true,
},
});
if (process.env.NODE_ENV === "development") {
win.loadURL("http://localhost:5173");
} else {
win.loadFile(path.join(__dirname, "../../build/renderer/index.html"));
}
};
app.whenReady().then(() => {
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
Using Inter-Process Communication
Renderer to Main (One-Way)
1
2
Renderer to Main (Two-Way)
1
2
Main to Renderer (One-Way)
1
2
Last updated