Main vs Renderer Process
Understanding Electron's Architecture
Electron apps have two types of processes: the main process and renderer processes. Understanding the difference between these processes is crucial for building Electron applications effectively.
The main process manages the application lifecycle, while renderer processes handle the user interface.
The Main Process
The main process is the entry point of your Electron application. It runs in a Node.js environment and has access to all Node.js APIs.
- Main process: Node.js environment - Full access to Node.js APIs and modules
- Application lifecycle - Controls when the app starts and quits
- Window management - Creates and manages BrowserWindow instances
- Native features - Access to native menus, dialogs, and system tray
- Single instance - Only one main process runs per application
// main.js
const { app, BrowserWindow } = require('electron');
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600
});
win.loadFile('index.html');
}
The Renderer Process
Each BrowserWindow instance runs its own renderer process. Renderer processes are responsible for rendering web pages and handling user interactions.
- Renderer process: Browser environment - Chromium rendering engine for displaying web content
- Web content - Renders HTML, CSS, and JavaScript
- Multiple instances - Each window or webview has its own renderer process
- Isolated by default - Limited access to Node.js for security reasons
- UI handling - Manages user interface and interactions
// renderer.js
// Running in the renderer process
document.getElementById('button').addEventListener('click', () => {
console.log('Button clicked in renderer process');
});
Inter-Process Communication (IPC)
Since the main and renderer processes are separate, Electron provides IPC (Inter-Process Communication) mechanisms to communicate between them:
- Use
ipcMainin the main process to receive messages - Use
ipcRendererin renderer processes to send and receive messages - Implement a preload script for secure communication
Process Separation Benefits
The dual-process architecture provides several advantages:
- Security - Isolates web content from system resources
- Stability - A crash in one renderer doesn't affect other windows
- Performance - Parallel processing and better resource management
- Sandboxing - Renderer processes can be sandboxed for security