October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
browser APIs

How to Build a Screen Capture API Demo with the Browser Screen Capture API

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To capture a screen in a web app, call navigator.mediaDevices.getDisplayMedia() from a user-initiated action, show its returned MediaStream in a <video> element, and provide a clear way to stop sharing. The browser—not your page—lets the user choose a tab, window, or display. This demo covers local preview; recording and live delivery are separate steps.

What this demo does—and what it does not

The Screen Capture API provides the capture stream, not a saved video or a complete video-call system. MDN describes it as an extension to Media Capture and Streams that lets a user select a screen or portion of one, such as a window, for capture. You can preview that stream locally, record it with the MediaStream Recording API, or send it through WebRTC. Those are distinct outcomes with additional implementation requirements.

The example below requests video only. That keeps the first version focused: the user chooses a source, the page previews it, and either the page or the user stops sharing. A screen capture can show sensitive information, so make the sharing state visible and make the stop control easy to find.

Requirements before you start

  • Use a secure context. Serve the page over HTTPS, or use a browser-recognized local development context.
  • Start from a user action. Call getDisplayMedia() directly in response to a click or another clear user gesture. Do not trigger it automatically on page load.
  • Allow the feature where necessary. A page restricted by Permissions Policy cannot capture. If the demo is embedded, the parent page may need to grant display capture to the iframe with its allow attribute, as well as satisfy the applicable policy.
  • Check compatibility for your audience. Support is limited and varies by browser and operating system. Consult MDN’s live compatibility information for the browsers and versions you intend to support; do not promise universal availability.

The browser displays its own chooser and asks the user to confirm a source. Your site cannot silently select a screen, enumerate available screens like cameras, or narrow the chooser to force a specific source.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Build a local screen-preview demo

Save this as an HTML file and serve it in a secure context. The page uses a button click to request capture, assigns the resulting stream to the video preview, and stops every track when the user selects Stop. It also reacts when the user ends sharing in browser chrome.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Screen capture demo</title>
  <style>
    body { font: 16px/1.5 system-ui, sans-serif; max-width: 52rem; margin: 2rem auto; padding: 0 1rem; }
    video { display: block; width: 100%; max-height: 70vh; background: #222; margin: 1rem 0; }
    button { margin-right: .5rem; padding: .55rem .9rem; }
    #status { min-height: 1.5em; }
  </style>
</head>
<body>
  <h1>Screen capture demo</h1>
  <p>Choose what to share in the browser dialog. Check the selected screen for private information first.</p>
  <button id="start" type="button">Start capture</button>
  <button id="stop" type="button" disabled>Stop capture</button>
  <p id="status" role="status" aria-live="polite">Not sharing.</p>
  <video id="preview" autoplay playsinline muted></video>

  <script>
    const startButton = document.querySelector("#start");
    const stopButton = document.querySelector("#stop");
    const preview = document.querySelector("#preview");
    const status = document.querySelector("#status");
    let activeStream = null;

    function setCaptureState(isSharing) {
      startButton.disabled = isSharing;
      stopButton.disabled = !isSharing;
      status.textContent = isSharing ? "Sharing is active." : "Not sharing.";
    }

    function stopCapture() {
      if (activeStream) {
        activeStream.getTracks().forEach((track) => track.stop());
        activeStream = null;
      }
      preview.srcObject = null;
      setCaptureState(false);
    }

    async function startCapture() {
      if (!navigator.mediaDevices?.getDisplayMedia) {
        status.textContent = "Screen capture is not available in this browser or context.";
        return;
      }

      try {
        const stream = await navigator.mediaDevices.getDisplayMedia({
          video: true,
          audio: false,
        });
        activeStream = stream;
        preview.srcObject = stream;
        await preview.play();

        const [videoTrack] = stream.getVideoTracks();
        if (videoTrack) {
          videoTrack.addEventListener("ended", stopCapture, { once: true });
        }
        setCaptureState(true);
      } catch (error) {
        if (error.name === "NotAllowedError") {
          status.textContent = "Capture was cancelled or not permitted. Choose a source and allow sharing to continue.";
        } else if (error.name === "NotFoundError") {
          status.textContent = "No capturable display source was available.";
        } else {
          status.textContent = `Could not start capture: ${error.message || error.name}`;
        }
        setCaptureState(false);
      }
    }

    startButton.addEventListener("click", startCapture);
    stopButton.addEventListener("click", stopCapture);
  </script>
</body>
</html>

How the capture lifecycle works

  1. The user clicks Start capture, providing the required interaction.
  2. The browser opens its source picker. The user chooses and confirms a tab, window, or display.
  3. The promise resolves with a MediaStream. The page assigns it to preview.srcObject; muted avoids feedback from local playback.
  4. Clicking Stop capture stops all stream tracks and clears the preview. If the user stops sharing from browser controls instead, the video track’s ended event resets the page state.

Cancellation and permission or policy failures are normal outcomes, not impossible states. The page should explain the result and let the user try again. The code is a minimal implementation pattern; test it in the browsers and embedding contexts you plan to support.

Recording, audio, and live sharing are separate choices

Local preview

The demo above only displays the stream in the current page. It does not upload or save the captured content.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Recording for playback or download

To create a recording, pass the stream to the MediaStream Recording API’s MediaRecorder, collect the resulting data, and offer it for download or send it to a storage service. Choose a MIME type supported by the target browser, checking support rather than assuming a single format works everywhere. The capture API itself does not provide a recording-storage service.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sharing with another person

For live remote sharing, add a WebRTC connection and the surrounding application flow, including a way for participants to establish the connection. getDisplayMedia() supplies the local stream; it is not a signaling service or a complete conferencing system.

Requesting audio

Set audio: true only if the demo needs to request audio. The browser may still return no audio track: availability depends on browser, platform, and the surface the user chooses. Inspect stream.getAudioTracks().length before displaying an audio-enabled state. Do not promise system audio until you have validated the browser-and-OS combinations you support.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Options and source-selection limits

The options passed to getDisplayMedia() can express preferences or request tracks, but they do not replace the browser’s source picker. Hints such as preferring the current tab or offering surface switching may affect browser behavior where supported; they cannot force the user to share a particular tab or hide other eligible choices. Check the current MDN method reference before relying on a particular option across browsers.

Decision What it means for the demo
Tab, window, or full display The user chooses in browser UI. A full display can expose more background content; a tab can limit what is visible, but the page cannot silently force the choice.
Video only or request audio Video-only is a simpler starting point. Requested audio may be absent, depending on browser, operating system, and selected surface.
Native API or an abstraction The browser-native API is enough for a small preview demo. Consider a third-party layer only if a larger product needs broader browser handling, transport, recording infrastructure, or support.

Privacy and interface details that matter

  • Tell users what the capture is for before the browser chooser opens.
  • Remind them to close sensitive documents, messages, or background windows they do not intend to expose.
  • Show a clear active-sharing state and keep Stop visible while capture is running.
  • Handle browser-side stopping so the page does not falsely claim capture is still active.
  • Request only the tracks the feature needs. Do not imply that a browser permission grants access to a hidden or preselected source.

The browser controls its sharing indicator and confirmation interface. Your page should complement those safeguards with honest status and an obvious exit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshooting common failures

  • getDisplayMedia is undefined: The browser may not support the API, the page may not be in a secure context, or the feature may be unavailable in that environment. Check window.isSecureContext, use HTTPS or an appropriate local context, and check compatibility for the target browser.
  • The request fails inside an iframe: Check the parent document’s Permissions Policy for display-capture and the iframe’s allow attribute. The embedding site may need to explicitly permit capture.
  • The chooser does not appear: Call the method directly from a fresh user action. An automatic page-load call or delayed action may not retain the required transient user activation.
  • The user cancels or denies the chooser: Treat this as an expected outcome. Keep the interface usable, explain that no source was shared, and let the user initiate another request.
  • The video is blank or playback rejects: Confirm the request resolved, that the stream has a video track, and that it was assigned to srcObject. Await preview.play() and report a playback error instead of silently claiming success.
  • Audio is missing: Check stream.getAudioTracks(). A successful video capture does not guarantee that the selected surface or browser provides audio.
  • The page still says sharing after the user stops in browser chrome: Listen for the capture track’s ended event and reset the buttons, status, and preview, as the example does.

Performance and reliability notes

Screen capture can involve large, changing frames, so avoid adding recording, encoding, or network transmission until the preview flow works. Those later steps have their own CPU, memory, bandwidth, and storage implications; the browser capture API does not remove those costs. Stop tracks as soon as the user is done, and test the behavior on the actual browser and operating-system combinations your app supports. There is no single cross-browser guarantee for audio or every chooser option.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If what you need is a screenshot of a web page rather than a live, user-selected desktop stream, ScreenshotNeo provides a website screenshot API and MCP server for developers. One GET request returns a PNG, JPEG, WebP, or PDF. For example, this cURL request saves a WebP capture of Stripe:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for setup and options. It removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots, and the Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. This is for capturing website pages, not replacing the browser’s interactive screen-sharing chooser.

Sign up free for 1,000 screenshots a month with no card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can a web page choose the screen or tab for the user?

No. The browser’s own chooser controls source selection and asks the user to confirm.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Does the Screen Capture API save a video file?

No. It returns a stream. Recording and storage require additional APIs and application logic.

Will requesting audio always capture system sound?

No. Audio availability varies by browser, operating system, and selected surface.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.