Screen Capture and Media
Explore how to access screen capture capabilities, media devices, and integrate them into your Electron desktop applications.
Accessing Camera & Screen
Electron lets your desktop app use native features like cameras, microphones, and even capture the screen. This opens up possibilities for video calls, screen recording, and more!
We'll explore how to list available devices, display live camera feeds, and capture your desktop or specific windows.
Discovering Your Devices
Before using a camera or microphone, you can discover what's available on the user's system. The navigator.mediaDevices.enumerateDevices() method provides a list of all connected media input and output devices.
Run this code to see your devices. You might need to grant permission to access devices.
const { app, BrowserWindow } = require('electron');
function createWindow() {
const win = new BrowserWindow({
width: 600,
height: 450,
webPreferences: {
nodeIntegration: true,
contextIsolation: false // Simplifies example for A1. Use preload scripts for security in real apps.
}
});
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Media Devices</title>
</head>
<body>
<h1>Available Media Devices</h1>
<ul id="device-list"></ul>
<script>
async function getMediaDevices() {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
const list = document.getElementById('device-list');
if (devices.length === 0) {
list.innerHTML = '<li>No media devices found or permission denied.</li>';
return;
}
devices.forEach(device => {
const li = document.createElement('li');
li.textContent = `Kind: ${device.kind}, Label: ${device.label || 'Unknown'}`;
list.appendChild(li);
});
} catch (err) {
console.error('Error listing devices:', err);
document.getElementById('device-list').innerHTML = `<li>Error: ${err.message}</li>`;
}
}
getMediaDevices();
</script>
</body>
</html>
`;
win.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(htmlContent)}`);
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => app.quit());
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});All lessons in this course
- Working with Native Modules
- Tray Applications & Badges
- Screen Capture and Media
- Power and Hardware Monitoring