Building desktop applications has never been easier thanks to frameworks like Electron. This powerful tool allows developers to create cross-platform applications using familiar web technologies: HTML, CSS, and JavaScript. In this article, we’ll explore how to leverage Electron for a practical project—a desktop screen recorder—while also addressing the common criticisms of the framework.
What is Electron?
Electron is an open-source framework created by GitHub. It combines Chromium and Node.js, enabling developers to build rich desktop applications with web technologies. This means that developers can use their existing web development skills to create applications that work seamlessly on Windows, macOS, and Linux.
Pros and Cons of Using Electron
Before diving into building your first app, it’s important to understand the advantages and disadvantages of using Electron:
Pros:
- Cross-Platform Compatibility: Write once, run everywhere. Electron apps can be deployed on any major operating system without platform-specific modifications.
- Familiar Technologies: Developers can use HTML, CSS, and JavaScript, reducing the learning curve.
- Rich User Interfaces: Leveraging web technologies allows for sophisticated UIs that can be updated easily.
- Access to Node.js APIs: Allows developers to incorporate powerful features and functionalities into their apps.
Cons:
- Large Application Size: Electron applications bundle the Chromium browser and Node.js, resulting in larger file sizes, even for simple apps.
- Resource Intensive: Running an entire Chromium instance can consume more CPU and RAM compared to native applications coded in languages like C# or Objective-C.
- Performance Concerns: Depending on how the app is designed, performance may lag behind that of native programs.
Despite these drawbacks, many developers—including those in large companies—choose Electron for its ease of use and the power of building desktop apps quickly. As Winston Churchill famously said, “Electron is the worst desktop architecture except for all the others we’ve tried.”
Building a Simple Desktop Screen Recorder
In this guide, we will create a simple desktop screen recorder using Electron. This project will cover various aspects of Electron and demonstrate how to integrate web APIs and Node.js functionality.
Getting Started
To begin, make sure you have Node.js installed. You can get started by setting up your Electron project using Electron Forge.
- Open your command line terminal.
- Run the following command to create a new project:
npx create-electron-app my-screen-recorder
- Navigate to the project directory:
cd my-screen-recorder
- Install the necessary packages:
npm install electron --save-dev
- Start the application:
npm start
Creating the User Interface
Now that we have our basic Electron app set up, let’s create a minimal user interface. Open the index.html
file and modify it to include:
- A video element to preview the recorded screen.
- Buttons for starting and stopping the recording.
- A button for selecting the video source.
<!DOCTYPE html>
<html>
<head>
<title>Screen Recorder</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.3/css/bulma.min.css">
</head>
<body>
<section class="section">
<div class="container">
<h1 class="title">Screen Recorder</h1>
<video id="preview" width="640" height="480" autoplay></video>
<br />
<button id="selectSource" class="button is-primary">Select Source</button>
<button id="startRecording" class="button is-success">Start Recording</button>
<button id="stopRecording" class="button is-danger">Stop Recording</button>
</div>
</section>
</body>
</html>
Implementing the Functionality
Next, we will write functionality that allows users to select a screen, record video, and save the recorded file. We will use the MediaRecorder API for this functionality, alongside Electron’s desktop capturing capabilities. Add the following to your renderer.js
:
const { desktopCapturer } = require('electron');
let mediaRecorder;
let recordedChunks = [];
document.getElementById('selectSource').addEventListener('click', getVideoSources);
async function getVideoSources() {
const sources = await desktopCapturer.getSources({ types: ['screen'] });
const menu = sources.map(source => ({
label: source.name,
click: () => selectSource(source)
}));
const template = [...menu];
const menu = Menu.buildFromTemplate(template);
menu.popup();
}
function selectSource(source) {
// Set up the video stream and MediaRecorder here.
// ...
}
This code sets up an event listener on the “Select Source” button, allowing users to choose a screen to record.
Recording Video
After selecting a source, setup the MediaRecorder
:
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.start();
}
function handleDataAvailable(event) {
if (event.data.size > 0) {
recordedChunks.push(event.data);
}
}
// Finish recording and save the file
Saving Recorded Video
To save the video, we need to prompt for a file location and write the recorded data to that file using Node.js’ fs
module.
const { dialog } = require('electron').remote;
const fs = require('fs');
mediaRecorder.onstop = async () => {
const blob = new Blob(recordedChunks, { type: 'video/webm' });
const buffer = Buffer.from(await blob.arrayBuffer());
const filePath = await dialog.showSaveDialog({
buttonLabel: 'Save Video',
filters: [{ name: 'Videos', extensions: ['webm'] }]
});
fs.writeFile(filePath, buffer, (err) => {
if (err) return console.log(err);
console.log('Video saved successfully!');
});
};
Packaging Your Application
Once you are satisfied with your screen recorder app, you can package it for distribution using Electron Forge. Run the following command to build your application:
npm run make
This will create executables for the desired operating systems, allowing others to install and use your application easily.
Conclusion
With just a few lines of code and some basic setups, you can create a professional desktop application using Electron. The ability to use web development skills to build cross-platform desktop apps is a game changer for many developers. Whether you’re creating a simple application like a screen recorder or something much more complex, Electron provides the tools you need.
For those who are familiar with JavaScript, building desktop apps with Electron can be both fun and rewarding. Have you tried building an app with Electron? Share your thoughts and experiences in the comments below!