Let’s say you’re fed up of the state of screen recorders’ paywalls and limitations and want to go on coding your own – it turns out you can already have basic functionnalities in a few lines of code.
We can ask the browser to get the capture video stream for us using the screen capture API, but for security reasons we must ensure a user gesture triggered the capture, for example a button click:
const button = document.createElement("button");
button.innerHTML = "capture";
document.body.append(button);
button.addEventListener("click", async () => {
// TODO
});
On click, get the video stream and record it
const stream = await navigator.mediaDevices.getDisplayMedia();
const recoder = new MediaRecorder(stream);
recoder.start();
Stop the recording when the user stops sharing the screen
const [video] = stream.getVideoTracks();
video.addEventListener("ended", () => {
recoder.stop();
});
Obtain the recorded file and download it
recoder.addEventListener("dataavailable", (evt) => {
const a = document.createElement("a");
a.href = URL.createObjectURL(evt.data);
a.download = "capture.webm";
a.click();
});
And voilĂ , you have a simple screen recorder!
It has many limitations that would be fun to resolve – audio recording, webcam integration, long running streams, etc – but I just found that doing such a powerful thing already with so few lines of code was too awesome not to share.