Build a Screen Capture API Demo in the Browser
In this article
Build a screen capture API demo in the browser using the built-in Screen Capture API to record a user's screen or specific tab directly in JavaScript. This feature enables web applications to capture screen content for demos, tutorials, or collaboration tools without requiring third-party software. The demo uses modern browser APIs and runs entirely client-side, ensuring privacy and performance. You’ll create a working prototype that starts and stops screen recording, displays the stream, and downloads the result as a video file.
What You'll Need
- A modern browser that supports the Screen Capture API (Chrome, Edge, or Firefox)
- A code editor (like VS Code, Sublime Text, or Notepad++)
- Basic knowledge of HTML, CSS, and JavaScript
- A local web server (optional but recommended for testing)
Step-by-Step
- Create a new folder for your project and open it in your code editor. This keeps all files organized.
- Create an
index.htmlfile. Add the basic HTML structure:<!DOCTYPE html>,<html>,<head>, and<body>. Set the title to "Screen Capture Demo". - Inside the
<body>, add a<video>element withid="video"andcontrolsso users can play, pause, and adjust volume. Setwidth="800"for visibility. - Add two buttons: one with
id="startBtn"and text "Start Capture", and another withid="stopBtn"and text "Stop Capture". Initially, disable the stop button with thedisabledattribute. - Create a
<script>tag at the bottom of the<body>to write your JavaScript code. - Inside the script, select the video and button elements using
document.getElementById(). Store references in variables likevideo,startBtn, andstopBtn. - Define a variable
mediaRecorderand set it tonull. This will hold the MediaRecorder instance once created. - Define a variable
chunksas an empty array. This will store recorded video data chunks. - Add a click event listener to
startBtn. Inside the handler, callnavigator.mediaDevices.getDisplayMedia({ video: true }). This triggers the browser’s screen selection prompt. - Use
.then()to handle the returned media stream. Assign it to the video element usingvideo.srcObject = stream. - Create a new
MediaRecorderinstance using the stream:new MediaRecorder(stream). Assign it to themediaRecordervariable. - Set up the
ondataavailableevent of themediaRecorderto push each data chunk into thechunksarray:mediaRecorder.ondataavailable = event => chunks.push(event.data);. - Set up the
onstopevent to create a downloadable video file when recording ends. Inside, create aBlobfrom thechunksarray with type'video/webm'. Then generate a URL usingURL.createObjectURL(blob)and assign it tovideo.srcso the recorded video can be played back. - Call
mediaRecorder.start()to begin recording immediately after setup. - Enable the
stopBtnand disable thestartBtnto prevent multiple recordings from starting. - Add a click event listener to
stopBtn. Inside, callmediaRecorder.stop()to end recording. Then stop all tracks on the stream usingstream.getTracks().forEach(track => track.stop())to free up resources. - After stopping, disable the
stopBtnand re-enable thestartBtnfor future use. - Save the HTML file and open it in your browser. For best results, serve it over HTTP (not file://) using a local server like Live Server in VS Code or Python’s
python -m http.server. - Click "Start Capture", choose a screen or tab in the browser prompt, and allow access. The video will display the live feed.
- Click "Stop Capture" to end recording. The video element will switch to playing back the recorded clip.
Common Mistakes
Forgetting to stop media tracks after recording leaves the camera or screen share active, which can cause performance issues or privacy concerns. Not handling the onstop event correctly may result in the recorded video not appearing. Using an incorrect MIME type in the Blob (like video/mp4 without proper codec support) can lead to playback failure. Starting the MediaRecorder before setting up event listeners means data events are missed. Assuming all browsers support the API without checking can cause errors in unsupported environments.
Tips
Always test on supported browsers—Chrome and Edge have the most reliable implementation. Use console.log to debug stream and recorder states. Clear the chunks array before each new recording to avoid mixing old data. Consider adding a download button that creates a temporary link using URL.createObjectURL and triggers a click event for saving the file. Wrap the getDisplayMedia call in a try-catch block to handle user denial or errors gracefully.
Troubleshooting
If the screen selection dialog doesn’t appear, ensure you’re using HTTPS or a local server (the API requires a secure context). If the video shows black or freezes, check that the stream is correctly assigned to srcObject and not src. If recording produces no data, verify that ondataavailable is set before calling start(). If playback fails, confirm the Blob MIME type matches the recorded format (WebM is safest). If buttons don’t respond, ensure event listeners are attached after the DOM loads—wrap script logic in a DOMContentLoaded event if needed.
Frequently Asked Questions
Which browsers support the Screen Capture API?
Chrome, Edge, and Firefox support it. Safari does not currently support getDisplayMedia.
Can I capture audio along with the screen?
Yes, by setting { video: true, audio: true } in getDisplayMedia, but audio capture may be limited by browser policies.
Why does the API require HTTPS?
Screen capture is a sensitive feature. Browsers require secure contexts (HTTPS or localhost) to prevent misuse.
Can I capture a specific window or just the whole screen?
The browser prompt lets users choose a tab, window, or entire screen—your code doesn’t control that directly.
What video format is recorded?
The MediaRecorder typically outputs WebM format, though this depends on browser support and settings.
Is it possible to stream the capture instead of saving it?
Yes, you can send chunks via WebSockets or WebRTC to stream in real time, but that requires additional backend or peer-to-peer setup.