In Electron, your application's architecture is divided into two main processes: the main process and the renderer process. The main process controls the application's lifecycle and native capabilities, while renderer processes are responsible for the user interface, essentially running web pages. Because these processes are distinct, they don't share memory. To communicate between them, we need to use Electron's Inter-Process Communication (IPC) module.
The most fundamental way to send messages between processes is using the ipcRenderer.send() and ipcMain.on() methods. The ipcRenderer.send() method is called from a renderer process to send a message to the main process. It takes two arguments: the channel name (a string identifier for the message) and the payload (any data you want to send).
import { ipcRenderer } from 'electron';
// In your renderer process (e.g., main.js, preload.js)
ipcRenderer.send('my-message', { data: 'Hello from renderer!' });On the other side, the main process listens for these messages using ipcMain.on(). This method also takes two arguments: the channel name (which must match the one used in ipcRenderer.send()) and a callback function. This callback function will be executed whenever a message is received on that channel. The callback receives two arguments: the event object and the payload that was sent from the renderer.
import { ipcMain, BrowserWindow } from 'electron';
// In your main process (e.g., main.js)
ipcMain.on('my-message', (event, payload) => {
console.log('Message received in main process:', payload);
// You can access the sender's window if needed: event.sender
});
// Example of creating a window that will use this IPC
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
});
win.loadFile('index.html');
}
app.whenReady().then(createWindow);It's crucial to remember that messages sent from the renderer process to the main process are asynchronous. This means that ipcRenderer.send() returns immediately, and the main process will handle the message at some point later. For scenarios where you need a response from the main process back to the renderer, we'll explore synchronous IPC and other patterns in later sections. For now, focus on understanding this one-way communication.