Inter-Process Communication (IPC) is the backbone of Electron applications, allowing the main process and renderer processes to communicate and share data. Understanding common use cases and adopting best practices ensures your application is efficient, responsive, and maintainable. Let's explore some of the most frequent scenarios where IPC shines.
- Sending User Input from Renderer to Main Process:
A very common task is capturing user input in a renderer process (like text from an input field or a button click) and sending it to the main process to perform an action, such as saving data, opening a file dialog, or making an API call. The ipcRenderer.send method is your go-to for this.
/* In renderer.js */
const { ipcRenderer } = require('electron');
document.getElementById('save-button').addEventListener('click', () => {
const content = document.getElementById('editor').value;
ipcRenderer.send('save-file', content);
});/* In main.js */
const { ipcMain } = require('electron');
ipcMain.on('save-file', (event, content) => {
// Logic to save the content to a file
console.log('Saving content:', content);
});- Updating the UI Based on Main Process Events:
Conversely, the main process often needs to inform the renderer process about state changes or events that require UI updates. This could be anything from a notification that a background task has completed to a change in application settings. The webContents.send method, often triggered by an ipcMain listener, is used here.
/* In main.js */
const { ipcMain } = require('electron');
function notifyRendererOfUpdate(win) {
win.webContents.send('update-available', { version: '1.2.3' });
}
// ... later, when an update is found
// notifyRendererOfUpdate(mainWindow);/* In renderer.js */
const { ipcRenderer } = require('electron');
ipcRenderer.on('update-available', (event, updateInfo) => {
console.log('Update available:', updateInfo.version);
// Display a notification to the user
});