Simple Screen Recorder in 20 lines of JavaScript

Nino Filiu - Nov 1 '23 - - Dev Community

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
});
Enter fullscreen mode Exit fullscreen mode

On click, get the video stream and record it

const stream = await navigator.mediaDevices.getDisplayMedia();
const recoder = new MediaRecorder(stream);
recoder.start();
Enter fullscreen mode Exit fullscreen mode

Stop the recording when the user stops sharing the screen

Image description

const [video] = stream.getVideoTracks();
video.addEventListener("ended", () => {
  recoder.stop();
});
Enter fullscreen mode Exit fullscreen mode

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();
});
Enter fullscreen mode Exit fullscreen mode

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.

codepen link

. . . . . . .