Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 36 ยท Media Capture and Streams

Screen Capture and Recording

Share a screen, window or tab with getDisplayMedia, handle the user stopping the share, and record any MediaStream to a file with MediaRecorder.

Two more capture tools complete the toolbox. getDisplayMedia() captures the screen, a window or a browser tab, the basis of every "Share screen" button. MediaRecorder records any MediaStream into a file, handy for voicemail, lesson recordings and local backups of a call. Both work on the same MediaStream objects you met earlier.

What runs here. Screen capture always requires a user choice in a browser dialog and a permission the preview does not have, so the getDisplayMedia code is shown read-only (the runnable demo prints the denial). Recording works fine on a synthetic stream, so MediaRecorder examples are live.

Sharing the screen

JavaScript
const stream = await navigator.mediaDevices.getDisplayMedia({
  video: { frameRate: { ideal: 15, max: 30 } },
  audio: true,                       // tab or system audio, if the browser offers it
});

The browser shows its own picker where the user chooses an entire screen, a window or a tab. You cannot pre-select or hide that choice, which is a deliberate privacy feature. Further rules:

  • It must be called from a user gesture (a click handler).
  • It works only in secure contexts (HTTPS, localhost).
  • The result is an ordinary stream: attach it to a <video> or send its tracks over a peer connection.
  • Audio is not guaranteed. Chrome can share tab audio (and system audio on some platforms); Safari and Firefox are more limited. Check stream.getAudioTracks().length.
  • Frame rate and size: a 1080p, 30 fps share is heavy. For slides use a low frame rate; for video playback use higher. Add contentHint to help the encoder:
JavaScript
const [track] = stream.getVideoTracks();
track.contentHint = 'detail';      // 'detail' or 'text' for slides/code, 'motion' for video

Knowing when the user stops sharing

Browsers show a "Stop sharing" bar. When the user clicks it, the track ends, and the ended event fires, because the source (the screen) ended outside your code:

JavaScript
track.addEventListener('ended', () => {
  shareButton.textContent = 'Share screen';
  showCamera();                       // go back to the camera
});

Always listen for it; otherwise the remote side sees a frozen last frame while your UI still says "sharing".

Sharing while on a call

Two choices:

  1. Replace the camera track on the existing sender with the screen track: await videoSender.replaceTrack(screenTrack). No renegotiation; the other side sees the screen instead of your face. Replace it back when the share ends.
  2. Add a second video track with pc.addTrack(screenTrack, screenStream), which triggers renegotiation but lets viewers see both your face and the screen at once (each track arrives in its own stream, so the UI can place them separately).

Handling the denial

getDisplayMedia and the denial path

When a user cancels the picker, you get NotAllowedError, the same name as a denied camera. Treat it as "no problem, they changed their mind", not as an error to shout about.

Recording with MediaRecorder

MediaRecorder takes a MediaStream, encodes it (WebM with VP8/VP9 and Opus in Chrome and Firefox; MP4 in Safari and newer Chrome) and delivers data in chunks:

JavaScript
const recorder = new MediaRecorder(stream, { mimeType: 'video/webm;codecs=vp8,opus' });
const chunks = [];
recorder.ondataavailable = (e) => { if (e.data.size) chunks.push(e.data); };
recorder.onstop = () => {
  const blob = new Blob(chunks, { type: recorder.mimeType });
  const url = URL.createObjectURL(blob);       // play it or offer it as a download
};
recorder.start();            // or start(1000) to get a chunk every second
// later
recorder.stop();

Always pick a MIME type the browser supports:

JavaScript
const candidates = ['video/webm;codecs=vp9,opus', 'video/webm;codecs=vp8,opus', 'video/mp4'];
const mimeType = candidates.find(t => MediaRecorder.isTypeSupported(t));

The next example records two seconds of a generated stream, then plays the recording back and reports facts about it.

Record a stream and play it back

If you want the recording to be downloadable, add an anchor with href = URL.createObjectURL(blob) and a download attribute. Release the URL later with URL.revokeObjectURL(url).

Gotchas when recording

  • Seeking: Chrome's WebM files lack a duration and seek index; players show an unknown length. Fix with a small library or server-side re-mux if you need accurate scrubbing.
  • Memory: collecting chunks in an array holds everything in RAM. For long recordings, upload each chunk as it arrives (start(5000)).
  • Codecs: record in the container your audience's players support; MP4 (H.264/AAC) is the most portable but not available in every browser.
  • What gets recorded: the stream's tracks as they are right now. If a track is disabled the recording contains silence/black.
  • Recording a call: record the remote stream (pc.ontrack) and/or a mixed local-plus-remote stream. For group calls, server-side recording from an SFU is more reliable than client recording.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can't a web page choose the screen to share without asking?

    The user must choose what to share through a browser-controlled dialog. Pages cannot pre-select or bypass it.
  2. 2. Which event tells you the user clicked the browser's 'Stop sharing' bar?

    When the source ends from outside your code, the track fires ended.
  3. 3. How do you share the screen during a call without renegotiating?

    replaceTrack swaps the media source on an existing sender, so no new offer/answer is needed.
  4. 4. Which method tells you whether MediaRecorder can use a given format?

    isTypeSupported checks a MIME type (with codecs) so you can fall back gracefully.

Summary

  • getDisplayMedia() shares a screen, window or tab; it needs a user gesture, always shows the browser's picker and may not include audio.
  • Listen for ended on the track to detect the user stopping the share, and use replaceTrack to swap camera and screen.
  • MediaRecorder turns any stream into chunks you assemble into a Blob; check isTypeSupported and stream long recordings to avoid memory problems.
  • Camera, microphone, canvas, Web Audio and screen sources all produce the same MediaStream type, so the rest of your code does not care where media came from.

Next: The RTCPeerConnection Life Cycle