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.
- First, we get the
stream
after we ask the user for permission. We pass thatstream
into a MediaRecorder. MediaRecorder is the API that allows us to save recording using theondataavailable
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.