docs.rodeo

MDN Web Docs mirror

MediaDevices: getDisplayMedia() method

{{APIRef("Screen Capture API")}} {{SecureContext_Header}} 

The getDisplayMedia() method of the {{domxref("MediaDevices")}}  interface prompts the user to select and grant permission to capture the contents of a display or portion thereof (such as a window) as a {{domxref("MediaStream")}} .

The resulting stream can then be recorded using the MediaStream Recording API or transmitted as part of a WebRTC session.

See Using the Screen Capture API for more details and an example.

Syntax

getDisplayMedia()
getDisplayMedia(options)

Parameters

[!NOTE] See the article Capabilities, constraints, and settings for a lot more detail on how these options work.

Return value

A {{jsxref("Promise")}}  that resolves to a {{domxref("MediaStream")}}  containing a video track whose contents come from a user-selected screen area, as well as an optional audio track.

[!NOTE] Browser support for audio tracks varies, both in terms of whether or not they’re supported at all by the media recorder and in terms of the audio sources supported. Check the compatibility table for details for each browser.

Exceptions

Security

Because getDisplayMedia() could be used in nefarious ways, it can be a source of significant privacy and security concerns. For that reason, the specification details measures browsers are required to take in order to fully support getDisplayMedia().

Examples

In the example below a startCapture() method is created, which initiates screen capture given a set of options specified by the displayMediaOptions parameter.

const displayMediaOptions = {
  video: {
    displaySurface: "browser",
  },
  audio: {
    suppressLocalAudioPlayback: false,
  },
  preferCurrentTab: false,
  selfBrowserSurface: "exclude",
  systemAudio: "include",
  surfaceSwitching: "include",
  monitorTypeSurfaces: "include",
};

async function startCapture(displayMediaOptions) {
  let captureStream;

  try {
    captureStream =
      await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
  } catch (err) {
    console.error(`Error: ${err}`);
  }
  return captureStream;
}

This uses {{jsxref("Operators/await", "await")}}  to asynchronously wait for getDisplayMedia() to resolve with a {{domxref("MediaStream")}}  which contains the display contents as requested by the specified options. The stream is then returned to the caller for use, perhaps for adding to a WebRTC call using {{domxref("RTCPeerConnection.addTrack()")}}  to add the video track from the stream.

[!NOTE] The Screen sharing controls demo provides a complete implementation that allows you to create a screen capture with your choice of getDisplayMedia() constraints and options.

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN