Electron APIs in Electron application
Focusing on core functionalities, here are examples categorized for clarity, demonstrating common use cases:
- I. App Lifecycle & Window Management:
- 1. app.on('ready', ...): This event listener is fundamental. It signifies that Electron is ready to create browser windows and load your application. All window creation and initialization should happen within this event handler.
- 2. app.quit(): The simplest way to cleanly exit your application. It's crucial to handle quit requests appropriately, for example, when the user clicks the close button.
- 3. BrowserWindow Class: This is the core API for creating and managing browser windows. Options allow customization (size, position, frameless, always-on-top, etc.). content_copyaddco
- II. Inter-Process Communication (IPC): Already covered in detail, but here's a concise example showing the basics.
- 4. ipcMain and ipcRenderer: Essential for communication between main and renderer processes.
- ◦ Main Process:
- ◦ Renderer Process:
- III. Menu and Tray:
- 5. Menu and MenuItem: For creating custom application menus. This requires creating the menu in the main process, and attaching events to menu items usually results in events sent to the renderer process for handling.
- 6. Tray: For creating system tray icons. Tray icons are also created and handled by the main process, with events to handle actions performed on the tray icon.
- IV. Dialog Boxes:
- 7. dialog.showOpenDialog(): Opens a file open dialog, allowing users to select files. The dialog is controlled by the main process, but often sends information to the renderer for processing.
- 8. dialog.showSaveDialog(): Similarly, presents a dialog to allow users to save files.
- V. Other Important APIs:
- 9. shell.openExternal(): Opens a URL in the user's default web browser.
- 10. autoUpdater (Electron Forge): Electron Forge typically provides a built-in autoUpdater API. This is used for automatic application updates, and it requires significant backend setup for the update server itself. This is not a native module but rather one you'd likely need to install via npm
1: import { app, BrowserWindow } from 'electron';
2:
3: let mainWindow: BrowserWindow | null = null;
4:
5: app.on('ready', () => {
6: mainWindow = new BrowserWindow({
7: width: 800,
8: height: 600,
9: webPreferences: {
10: // Node Integration (use with caution!)
11: nodeIntegration: false, // Generally recommended for security
12: contextIsolation: true, // For security
13: preload: path.join(__dirname, 'preload.js'), // Preload script for secure IPC
14: },
15: });
16: mainWindow.loadFile('index.html');
17: });
1: app.on('window-all-closed', () => {
2: if (process.platform !== 'darwin') { // macOS handles quit differently
3: app.quit();
4: }
5: });
1: const win = new BrowserWindow({
2: width: 800,
3: height: 600,
4: frame: false, // Frameless window
5: titleBarStyle: 'hidden', // macOS specific: Hidden title bar
6: transparent: true, // Transparent background (requires other styling)
7: // ... other window options
8: });
1: ipcMain.on('my-message', (event, args) => {
2: // Handle the message from the renderer process
3: console.log('Received:', args);
4: event.reply('reply-message', { response: 'Hello from main!' });
1: import { ipcRenderer } from 'electron';
2:
3: ipcRenderer.send('my-message', { data: 'Hello from renderer!' });
4: ipcRenderer.on('reply-message', (event, args) => {
5: console.log('Reply:', args);
6: });
1: const template = [
2: {
3: label: 'Application',
4: submenu: [
5: { label: 'Quit', accelerator: 'CmdOrCtrl+Q', click: () => app.quit() },
6: ],
7: },
8: // ... more menu items
9: ];
10: const menu = Menu.buildFromTemplate(template);
11: Menu.setApplicationMenu(menu); // Set the main menu
1: const tray = new Tray(path.join(__dirname, 'icon.png')); // Requires an icon file
2: const contextMenu = Menu.buildFromTemplate([
3: { label: 'Item1', click: () => {/* ... */ } },
4: { label: 'Item2', click: () => {/* ... */ } },
5: ]);
6: tray.setContextMenu(contextMenu);
1: const files = dialog.showOpenDialogSync(null, {
2: properties: ['openFile'],
3: filters: [{ name: 'Text Files', extensions: ['txt'] }],
4: });
1: const result = dialog.showSaveDialogSync(null, {
2: title: 'Save File',
3: defaultPath: 'mydocument.txt', // Example default path
4: });
1: shell.openExternal('https://www.example.com');
These examples provide a starting point. Remember that security and asynchronous operations are critically important when using Electron APIs. Always validate data received from the renderer process (and sanitize user inputs if the dialog boxes are used for receiving files). Also, use async/await or promises to properly manage asynchronicity and prevent blocking the main thread. Finally, be cautious of what permissions your app requests, especially those tied to OS interaction, as those permissions may vary between OS versions or distributions. Also, thoroughly test your application on multiple operating systems.
Electron context:
AngularElectron context:
|