Multi-Window Architectures
Design and implement complex multi-window Electron applications, managing inter-window communication and state effectively.
Why Multiple Windows?
Electron applications often benefit from using multiple windows. Think of a chat application: you might have a main contact list and separate windows for each active conversation.
- Separate Workflows: Isolate tasks into dedicated windows.
- User Preferences: A settings window distinct from the main application.
- Auxiliary Tools: Dedicated viewers, inspectors, or side panels.
- Enhanced User Experience: Provides flexibility and organization for complex apps.
Spawning a New Window
Creating additional windows in Electron is similar to creating your initial main window. You simply instantiate another BrowserWindow in your main process.
Here's how you can create a second window that loads a different HTML file.
const { app, BrowserWindow } = require('electron');
const path = require('path');
let mainWindow;
let secondWindow;
function createMainWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
});
mainWindow.loadFile('index.html');
}
function createSecondWindow() {
secondWindow = new BrowserWindow({
width: 400,
height: 300,
parent: mainWindow, // Optional: make it a child window
modal: false, // Optional: for modal behavior
show: false, // Don't show immediately
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload_second.js')
}
});
secondWindow.loadFile('second.html');
secondWindow.once('ready-to-show', () => {
secondWindow.show();
});
}
app.whenReady().then(() => {
createMainWindow();
createSecondWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createMainWindow();
}
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});All lessons in this course
- Multi-Window Architectures
- Background Processes and Workers
- Integrating with Cloud Services
- Auto-Updating Your Electron App