How to take a video or screenshot of a user’s screen in Javascript

In this quick guide, I will show you a straightforward and effective way to record the user’s screen and play it back using MediaDevices.getDisplayMedia().

Step 1: Setup HTML UI

Our UI simply consists of a start recording button, stop button and a replay button.

Step 2: When you click “Start Recording”, prompt and record the user’s screen.

First set up a click handler to start things off.

Step 3: Start Recording

To actually start recording, you will call this method navigator.mediaDevices.getDisplayMedia() to ask the user for permission to record their screen. You can pass a constraint object to use audio or video, for details see: https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints.

It returns a Promise with a stream of video tracks which can be fed into the video element to play it back to the user.

Step 3: Add recording ability to the start recording method.

The recording works in 3parts.

  1. First, we get the stream after we ask the user for permission. We pass that stream into a MediaRecorder. MediaRecorder is the API that allows us to save recording using the ondataavailable event handler as shown in the next step.

stream = await navigator.mediaDevices.getDisplayMedia()

recorder = new MediaRecorder(stream);

2. Second, listen for when the recordings are available using ondataavailable which will contain the recorded media as a BLOB.

recorder.ondataavailable = e => chunks.push(e.data);

3. Last, when the recordings are fully done we can play it back by assigning the src value and calling video.play()

recorder.onstop = e => {const completeBlob = new Blob(recordedSlices, {type: recordedSlices[0].type});video.src = URL.createObjectURL(completeBlob);video.play();};

Conclusion:

Thanks for checking out my article, follow me for more ways to level up your engineering skills.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mike Guoynes

Mike Guoynes

Hey I’m Mike, I’m a senior frontend engineer that enjoys discovering real-world problems and then designing & building useful products alongside great people.