Learn Electron · 8/12

Hardware and OS Interaction

9 min read

Welcome! If you are building a web application, you are safely contained inside a sandbox. But when you step into the world of Electron, you are no longer just a website—you are a full-fledged desktop application. You have the keys to the kingdom. You can talk to the operating system, hijack the keyboard, keep the screen awake, and look through the webcam.

With great power comes a lot of configuration files and permission handling.

In this guide, we are going to learn how to interact with the underlying hardware and OS like a professional. Let's start by laying the groundwork.


🛠️ The Standard Setup (Boilerplate)

Before we interact with the hardware, we need an Electron project structure using modern security standards (Context Isolation enabled). If you haven't set up an Electron project recently, here is the 2026-standard minimal setup.

1. Install Electron:

bash
npm init -y
npm install electron --save-dev

2. Standard File Structure:
We will use three main files to separate concerns securely.

  • main.js: The backend (Node.js/OS access).
  • preload.js: The bridge (Context Bridge).
  • renderer.js: The frontend (Web APIs).

(We will progressively add code to these files as we learn the concepts.)


1. Accessing Webcams and Microphones Safely 📷🎤

Definition

Accessing webcams and microphones involves capturing raw audio and video input directly from the physical hardware connected to the computer using the navigator.mediaDevices.getUserMedia API, combined with Electron's permission request handlers.

The Problem

In a standard Chrome browser, when a website wants to use your camera, a neat little popup appears asking for your permission. In Electron, you are the browser. If you do not explicitly handle permission requests, one of two things will happen:

  1. The OS will silently block your app, and you will spend four hours wondering why your video stream is black.
  2. The camera turns on automatically without warning the user, which is a massive privacy violation.

The Concept (The Solution)

To solve this, we must intercept the permission request in the main process and grant or deny it based on our app's logic. Then, we can use standard web APIs in the renderer process to capture the stream.

(Imagine you are the security guard at an office building. You have a visitor (the renderer process) asking to access the surveillance room. If you just wave them in without checking their clearance, you're going to get fired. You need a systematic way to verify permissions before handing over the keys.)

How to implement it

Step 1: Handle Permissions in main.js
We use session.setPermissionRequestHandler to approve or deny the request safely.

javascript
// main.js
const { app, BrowserWindow, session } = require('electron');
const path = require('path');

app.whenReady().then(() => {
  const mainWindow = new BrowserWindow({
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  });

  // Intercept permission requests
  session.defaultSession.setPermissionRequestHandler((webContents, permission, callback) => {
    const allowedPermissions = ['media']; // 'media' covers camera and microphone

    if (allowedPermissions.includes(permission)) {
      callback(true); // Approve
    } else {
      callback(false); // Deny
    }
  });

  mainWindow.loadFile('index.html');
});

Step 2: Access the Media in renderer.js
Once approved, we use the standard WebRTC API to get the video feed.

javascript
// renderer.js
async function startWebcam() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ 
        video: true, 
        audio: true 
    });
    
    const videoElement = document.getElementById('my-video');
    videoElement.srcObject = stream;
    videoElement.play();
  } catch (err) {
    console.error('Camera access denied or failed:', err);
  }
}

startWebcam();

🧠 Industry Standard Fact: On macOS, code alone isn't enough. Apple is fiercely protective of user privacy. If your app attempts to access the camera without having the NSCameraUsageDescription and NSMicrophoneUsageDescription strings inside your app's Info.plist file (which you configure in your build tools like electron-builder), the macOS system will instantly crash your app. Boom. Gone. Always configure your plist!


2. Capturing the Screen: Using desktopCapturer 🖥️

Definition

desktopCapturer is an Electron module that gathers information about available media sources (screens, displays, and individual application windows) that can be captured as video or audio streams.

The Problem

You want to build the next Discord or Zoom, allowing users to share their screens. In standard browsers, calling getDisplayMedia() opens a built-in OS dialog letting the user pick what to share. Electron does not provide this dialog. Furthermore, older versions of Electron let the frontend code directly fetch all open windows, which was a massive security vulnerability (imagine a malicious script scraping your bank details from another open window).

The Concept (The Solution)

Modern Electron requires you to fetch the screen sources securely in the main process using desktopCapturer. You then send the list of sources to the renderer via IPC (Inter-Process Communication). Finally, the renderer passes the chosen source ID to navigator.mediaDevices.getUserMedia to start the actual recording.

How to implement it

Step 1: Fetch Sources in main.js

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

// We create a channel for the renderer to ask for screen sources
ipcMain.handle('get-screen-sources', async () => {
  const sources = await desktopCapturer.getSources({ 
      types: ['window', 'screen'],
      thumbnailSize: { width: 150, height: 150 } // Saves performance
  });
  
  // We only return what the frontend needs to map the UI
  return sources.map(source => ({
    id: source.id,
    name: source.name,
    thumbnail: source.thumbnail.toDataURL()
  }));
});

Step 2: Bridge the Communication in preload.js

javascript
// preload.js
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  getScreenSources: () => ipcRenderer.invoke('get-screen-sources')
});

Step 3: Capture the Screen in renderer.js

javascript
// renderer.js
async function captureScreen() {
  // 1. Get the sources from the main process
  const sources = await window.electronAPI.getScreenSources();
  
  // 2. For simplicity, let's just pick the first Entire Screen we find
  const selectedSource = sources.find(source => source.name === 'Entire Screen' || source.name === 'Screen 1');

  if (!selectedSource) return;

  // 3. Request the stream using the specific source ID
  try {
    const stream = await navigator.mediaDevices.getUserMedia({
      audio: false, 
      video: {
        mandatory: {
          chromeMediaSource: 'desktop',
          chromeMediaSourceId: selectedSource.id,
          minWidth: 1280,
          maxWidth: 1920,
          minHeight: 720,
          maxHeight: 1080
        }
      }
    });

    // Attach stream to a video element
    document.getElementById('screen-video').srcObject = stream;
  } catch (error) {
    console.error('Failed to capture screen:', error);
  }
}

💡 Fun Fact: If you try to capture system audio on macOS 14.2 or higher, Apple enforces a strict rule requiring the new CoreAudio Tap API. You must include the NSAudioCaptureUsageDescription key in your .plist. If you forget it, the audio stream won't throw an error—it will just be a dead, silent stream. The ultimate silent treatment from Apple!


3. Registering and Handling Global Keyboard Shortcuts ⌨️

Definition

A global shortcut is a keyboard combination that the operating system registers and routes to your application, even if your application is minimized or completely out of focus.

The Problem

Standard DOM event listeners (window.addEventListener('keydown', ...)) only work when your application window is actively focused by the user. If you are building a background music player and the user is typing an essay in Microsoft Word, hitting Ctrl+Space will just type a space. You need a way to bypass the window focus and grab the keystroke straight from the OS.

The Concept (The Solution)

Electron provides the globalShortcut module. It binds specific key combinations directly to the native operating system's event loop.

(Imagine you have a private walkie-talkie channel directly to the building manager. No matter what room you are in, if you push the button, the manager hears you instantly. That's a global shortcut.)

How to implement it

javascript
// main.js
const { app, globalShortcut } = require('electron');

app.whenReady().then(() => {
  // Register a global shortcut
  const success = globalShortcut.register('CommandOrControl+Shift+X', () => {
    console.log('Global shortcut triggered! Time to take a screenshot!');
  });

  if (!success) {
    console.error('Shortcut registration failed! Another app might be using it.');
  }
});

// VERY IMPORTANT: Clean up before quitting!
app.on('will-quit', () => {
  // Unregister all shortcuts so we don't hold the keys hostage
  globalShortcut.unregisterAll();
});

⚠️ Industry Practice: Always check if the registration was successful. Operating systems enforce a "first come, first served" rule. If Spotify already registered MediaPlayPause, your app silently fails to register it. Never fight the OS; provide users with a UI to customize their shortcuts!


4. Managing Power States and Preventing Sleep Mode ☕💻

Definition

Managing power states involves interacting with the operating system's power management system to block the computer from turning off the display or entering a low-power suspended state (sleep mode).

The Problem

Operating systems are highly optimized to save battery. If the user doesn't touch the mouse for 10 minutes, the OS goes to sleep. But what if your app is in the middle of downloading a 50GB file? Or what if your user is intensely watching a 2-hour tutorial video without touching the mouse? If the computer sleeps, the network connection drops, the download fails, and your user will likely throw their computer out the window.

The Concept (The Solution)

Electron uses the powerSaveBlocker module. It allows your app to file a request with the OS, essentially saying: "Hey, I am doing something critical here. Please keep the lights on until I tell you otherwise."

How to implement it

The powerSaveBlocker allows two types of blocks:

  1. prevent-app-suspension: Keeps the CPU and network alive, but allows the screen to turn off (Great for downloading files or playing background music).
  2. prevent-display-sleep: Keeps both the screen and the system fully awake (Great for playing video or presentations).
javascript
// main.js
const { powerSaveBlocker } = require('electron');

let blockerId;

function startHeavyDownload() {
  console.log('Starting heavy download...');
  
  // Request the OS to prevent the app from suspending
  blockerId = powerSaveBlocker.start('prevent-app-suspension');
  
  console.log(`Power save blocker started with ID: ${blockerId}`);
  console.log(`Is it active? ${powerSaveBlocker.isStarted(blockerId)}`);
}

function finishDownload() {
  console.log('Download complete!');
  
  // ALWAYS stop the blocker when done to save the user's battery
  if (powerSaveBlocker.isStarted(blockerId)) {
    powerSaveBlocker.stop(blockerId);
    console.log('Power save blocker stopped. The computer can sleep now.');
  }
}

⚖️ Good Citizen Rule: prevent-display-sleep uses significantly more battery than prevent-app-suspension. Always use the lowest power block you actually need, and always call .stop() the moment the task is complete. If you drain a user's laptop battery because you forgot to turn off the powerSaveBlocker, they will uninstall your app faster than you can say "Electron".


📚 Reference Documentation

To dive deeper into the API methods and edge cases, always consult the official Electron docs:

Challenge

Challenge: Configure Core OS Integrations in Electron's Main Process

You are tasked with completing the main.js file for a desktop application that requires deep OS-level integrations. Your goal is to correctly implement three critical features using Electron's APIs for security and functionality.

Requirements:

  1. Media Permission Handling: Configure the default session to automatically grant 'media' (camera and microphone) permissions. The application should not prompt the user; instead, it should programmatically approve these requests when they originate from its own web contents.

  2. Global Shortcut and Power Management:

    • Register a global keyboard shortcut for CommandOrControl+Alt+P.
    • When this shortcut is activated, the application must prevent the system's display from going to sleep. You must capture and store the ID returned by the power blocker.
  3. Graceful Shutdown and Cleanup:

    • When the application is about to quit (in the will-quit event), it must perform two cleanup actions:
      • Stop the active power-saving block using its stored ID.
      • Unregister all global shortcuts to release them back to the operating system.

Expected result

The completed main.js file must correctly use three separate Electron modules within the application lifecycle.

  1. Permission Handler: The code must implement session.defaultSession.setPermissionRequestHandler. The handler function receives (webContents, permission, callback) as arguments. Inside the handler, there should be a condition that checks if permission is strictly equal to 'media' and, if so, executes callback(true).

  2. Global Shortcut and Power Blocker: The globalShortcut.register method should be called with the accelerator string 'CommandOrControl+Alt+P' and a callback function. Inside this callback, the code must call powerSaveBlocker.start('prevent-display-sleep') and correctly assign its return value to the powerBlockerId variable.

  3. Cleanup: The 'will-quit' event listener must contain two calls:

    • A call to powerSaveBlocker.stop(powerBlockerId), which should be wrapped in a check to ensure powerBlockerId is not null or falsy.
    • A call to globalShortcut.unregisterAll() to release the keyboard hooks.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.