Learn Electron ยท 5/12

Native Operating System Integration

9 min read

Welcome to the bridge between the web and the metal! Building an Electron application means you get the best of both worlds: the styling and flexibility of web technologies, and the raw power of the underlying operating system.

Imagine you are running a pizza shop. The dining area, the tables, and the decorative menus are your HTML, CSS, and JavaScript. But when you need to ring the delivery bell, use the building's plumbing, or shout out the window to a customer, you need to interact with the building itself. Native OS Integration is how your web code talks to the underlying building (Windows, macOS, or Linux).

Before we dive into the specific features, let's set up the latest industry-standard boilerplate from the Electron documentation. All the native integrations we will discuss live in the Main Process (your Node.js environment), not the Renderer Process (your HTML UI).

javascript
// main.js - The Brain of your Application
const { app, BrowserWindow, Menu, dialog, Tray, Notification } = require('electron');
const path = require('node:path');

let mainWindow; // Keep global reference so it isn't garbage collected

app.whenReady().then(() => {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      // Security standard: Context Isolation is true by default in modern Electron
    }
  });
  
  mainWindow.loadFile('index.html');
  
  // We will add our native OS integrations here!
});

// Quit when all windows are closed, except on macOS (standard Apple behavior)
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

1. Crafting Custom Application and Context Menus ๐Ÿ“‹

The Definition and The Problem

An Application Menu is the persistent bar at the top of your screen or window (like File, Edit, View). A Context Menu is the graphical menu that appears upon user interaction, typically a right-click.

The Problem: Out of the box, Electron provides a default menu that is strictly for debugging (featuring options like "Toggle Developer Tools"). If you ship this to production, your users will see a bunch of developer jargon. Furthermore, standard web-based right-click menus do not behave or look like native desktop menus, which breaks the illusion that your app is a "real" desktop application.

The Solution: Electron's Menu and MenuItem modules allow you to override the default menus with native OS menus using a simple array of template objects.

Building an Application Menu

In the industry, we rarely build menus item by item. Instead, we use Menu.buildFromTemplate().

javascript
const { app, Menu } = require('electron');

const isMac = process.platform === 'darwin';

// 1. Define the template
const template = [
  // On macOS, the first menu is ALWAYS the App Name. 
  // We use a spread operator to conditionally add it.
  ...(isMac ? [{
    label: app.name,
    submenu: [
      { role: 'about' },
      { type: 'separator' },
      { role: 'quit' }
    ]
  }] : []),
  {
    label: 'File',
    submenu: [
      isMac ? { role: 'close' } : { role: 'quit' }
    ]
  },
  {
    label: 'Edit',
    submenu: [
      { role: 'undo' },
      { role: 'redo' },
      { type: 'separator' }, // Adds a nice horizontal line
      { role: 'copy' },
      { role: 'paste' }
    ]
  }
];

// 2. Build the menu
const menu = Menu.buildFromTemplate(template);

// 3. Set it as the application menu
Menu.setApplicationMenu(menu);

Industry Insight: Notice the role property? Instead of writing complex IPC (Inter-Process Communication) code to figure out how to copy text, you just pass role: 'copy'. Electron automatically maps this to the native OS copy command. Always use roles when available!

Building a Context Menu (Right-Click)

To trigger a context menu, your web UI (Renderer) needs to tell the Main process that a right-click happened.

javascript
// main.js
const { ipcMain } = require('electron');

ipcMain.on('show-context-menu', (event) => {
  const template = [
    { label: 'Save Image', click: () => { console.log('Saving...') } },
    { type: 'separator' },
    { role: 'copy' }
  ];
  const contextMenu = Menu.buildFromTemplate(template);
  
  // Popup the menu in the specific window that requested it
  contextMenu.popup({ window: BrowserWindow.fromWebContents(event.sender) });
});

2. Native System Dialogs: Open, Save, and Error Prompts ๐Ÿ—‚๏ธ

The Definition and The Problem

A System Dialog is a native operating system window used to prompt the user for input, select files, or display an alert.

The Problem: The HTML <input type="file"> element is incredibly restrictive. It forces a specific UI, restricts access to actual file system paths, and doesn't let you programmatically open the file picker. Similarly, using the web alert() function in a desktop app looks like a 1990s pop-up and locks the entire browser engine.

The Solution: The dialog module. It taps directly into the Windows File Explorer or macOS Finder dialogs, giving your app complete, native access to the file system.

Showing an Open File Dialog

Dialogs should almost always be attached to a specific BrowserWindow. This makes them "modal" (they dim the main window and lock it until the user chooses a file).

javascript
const { dialog } = require('electron');

async function handleFileOpen() {
  const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
    title: 'Select a cool image',
    buttonLabel: 'Import',
    filters: [
      { name: 'Images', extensions: ['jpg', 'png', 'gif'] }
    ],
    properties: ['openFile', 'multiSelections']
  });

  if (canceled) {
    console.log('User got cold feet and canceled.');
    return;
  } else {
    console.log('Selected files:', filePaths);
    return filePaths[0]; // You can now use Node.js `fs` module to read this path!
  }
}

Native Message Boxes

Need to show an error or ask for confirmation? Use showMessageBox.

javascript
async function showWarning() {
  const response = await dialog.showMessageBox(mainWindow, {
    type: 'warning', // Options: 'none', 'info', 'error', 'question', 'warning'
    title: 'Delete Database',
    message: 'Are you absolutely sure you want to delete everything?',
    detail: 'This action cannot be undone. Seriously.',
    buttons: ['Cancel', 'Delete Everything'], // Index 0 is Cancel, Index 1 is Delete
    defaultId: 0, // Highlight the "Cancel" button by default (safer)
    cancelId: 0   // If the user closes the window, it assumes Index 0
  });

  if (response.response === 1) {
    console.log('Initiating self-destruct sequence...');
  }
}

โš ๏ธ Industry Standard: Notice we use await and the Promise-based versions of the dialogs. Never use the synchronous versions like dialog.showOpenDialogSync(). They literally freeze the entire Node.js thread. If the user leaves the dialog open and walks away to make a sandwich, your whole application is frozen in time.


3. System Tray Icons and Background Applications โ˜•

The Definition and The Problem

The System Tray is the notification area on your OS taskbar (bottom-right on Windows, top-right menu bar on macOS) where background applications live.

The Problem: Desktop apps like Spotify, Slack, or Discord don't typically close completely when you hit the "X" button. They minimize to the background so they can continue receiving messages or playing music. Without OS integration, clicking "X" kills your HTML/JS process entirely.

The Solution: The Tray module allows you to put an icon in the system notification area, giving your application a persistent, background life.

Creating a Tray Icon

javascript
const { app, Tray, Menu, nativeImage } = require('electron');
const path = require('node:path');

// โš ๏ธ CRITICAL: Define tray in the global scope!
let tray = null; 

app.whenReady().then(() => {
  // Create a native image from your icon file
  const iconPath = path.join(__dirname, 'assets', 'icon.png');
  const trayIcon = nativeImage.createFromPath(iconPath);
  
  tray = new Tray(trayIcon);
  
  // Set what happens when the user hovers over the icon
  tray.setToolTip('My Awesome Background App');
  
  // Create a right-click menu for the tray
  const contextMenu = Menu.buildFromTemplate([
    { label: 'Open App', click: () => mainWindow.show() },
    { type: 'separator' },
    { label: 'Quit', click: () => {
        app.isQuiting = true;
        app.quit();
    }}
  ]);
  
  tray.setContextMenu(contextMenu);

  // Left-click behavior (Windows/Linux primarily)
  tray.on('click', () => {
    mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
  });
});

๐Ÿ—‘๏ธ The Garbage Collector Strikes!
Notice how we declared let tray = null; at the very top of the file, outside of the function? This is a famous rite of passage for Electron developers. If you declare your Tray inside the app.whenReady() function, the JavaScript Garbage Collector will see that the function finished, assume you don't need the variables anymore, and mercilessly eat your tray icon. Your icon will appear for 3 seconds and then vanish into the void. Always make your Tray a global variable!

macOS Pro-Tip: On macOS, name your icon file with the word Template at the end (e.g., iconTemplate.png). macOS will automatically invert the colors of the icon based on whether the user is using Light Mode or Dark Mode.


4. Triggering Native OS Notifications ๐Ÿ””

The Definition and The Problem

A Native Notification is a system-level alert box that slides onto the screen (via Windows Action Center or macOS Notification Center) to grab the user's attention.

The Problem: Web browsers have an HTML5 Notification API, but it only works if your browser window is actively running and rendering. If your app is minimized to the system tray (as we just learned above), your web-based notifications might fail.

The Solution: Electron's Notification module. It triggers notifications directly from the Main (Node.js) process, meaning they work perfectly even when the visual UI is hidden.

Firing a Notification

javascript
const { Notification } = require('electron');

function showOrderCompleteNotification() {
  // 1. Always check if the OS actually supports notifications first!
  if (!Notification.isSupported()) {
    console.log('Notifications are not supported on this system.');
    return;
  }

  // 2. Create the notification object
  const notif = new Notification({
    title: 'Pizza is Ready! ๐Ÿ•',
    body: 'Your large pepperoni has finished baking.',
    silent: false, // Set to true if you don't want the OS "ding" sound
    icon: path.join(__dirname, 'assets', 'pizza.png')
  });

  // 3. Listen for the user clicking the notification
  notif.on('click', () => {
    console.log('User clicked the notification!');
    mainWindow.show(); // Bring the app to the front
  });

  // 4. Actually display it
  notif.show();
}

Fun Fact for Windows Developers: Have you ever written the perfect notification code, ran it, and absolutely nothing happened? You didn't make a mistake! Windows 10/11 has a feature called "Focus Assist" or "Do Not Disturb" which aggressively blocks notifications. Furthermore, Windows requires your app to have a registered appId (usually set during installation or via app.setAppUserModelId()) for notifications to route correctly. If notifications fail on Windows, always check the OS settings first before debugging your code for hours!


Conclusion

By mastering Menus, Dialogs, Trays, and Notifications, you elevate your Electron app from feeling like a "website pretending to be software" to a fully integrated, first-class desktop citizen.

Remember the golden rules of OS integration:

  1. Native features belong in the Main Process.
  2. Never block the main thread with synchronous dialogs.
  3. Save your background features (like Trays) in global variables to outsmart the garbage collector.

References & Extra Reading

To dive deeper into the exact configurations and API parameters, consult the official Electron documentation (always stay updated with the latest version):

Challenge

Challenge Instructions

Your task is to write the main process code for an Electron application that runs primarily from the system tray. You must integrate native OS features like the tray, context menus, and dialogs.

Complete the createWindow function based on the following requirements:

  1. Global Tray Variable: Ensure the tray variable is declared in the global scope so it's not garbage collected when the createWindow function finishes execution.
  2. Tray Icon: Instantiate a new Tray. You can use a placeholder string like './icon.png' for the icon path.
  3. Context Menu Template: Create an array of menu item objects that will serve as the template for the tray's context menu. This template must include:
    • An item with the label 'Show App' that, when clicked, calls the show() method on the mainWindow instance.
    • An item with the label 'Show Info' that, when clicked, asynchronously calls dialog.showMessageBox() to display a native informational message.
    • An item with the label 'Open File' that, when clicked, asynchronously calls dialog.showOpenDialog() to open a native file picker, filtered to only show files with .txt and .md extensions.
    • A separator item.
    • An item that uses the built-in role property to quit the application.
  4. Build and Set Menu: Use Menu.buildFromTemplate() to create a menu from your template, and then use tray.setContextMenu() to attach it to your tray icon.

Expected result

Your code should correctly implement a system tray application within the createWindow function. The final code should feature:

  • A top-level, mutable variable (e.g., let tray = null;) to store the Tray instance.
  • Inside createWindow, this variable is assigned a new Tray() instance.
  • A constant variable (e.g., contextMenuTemplate) assigned an array of objects defining the menu structure.
  • The menu item for showing info must use async () => { await dialog.showMessageBox(...) }.
  • The menu item for opening a file must use async () => { await dialog.showOpenDialog(...) } and include the filters property in its options object.
  • The quit menu item must be configured with { role: 'quit' }.
  • A final call to Menu.buildFromTemplate() with the template, and the result passed to tray.setContextMenu().
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.