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

To preview a webcam in a web page, call navigator.mediaDevices.getUserMedia({ video: true, audio: false }) after a user clicks a button, assign the returned MediaStream to a <video> element’s srcObject, and stop its tracks when finished. The page must run in HTTPS (or a documented secure local context such as localhost), and the user must grant camera permission.

This complete example answers “How do I preview my webcam in the browser?” without requesting microphone access. It also covers camera selection, resolution constraints, iframes, autoplay, errors, cleanup, and production troubleshooting.

Working webcam preview: complete HTML and JavaScript

Save this as an HTML page and serve it from HTTPS or http://localhost. Opening a local file may work in some browsers, but secure-context behavior is the reliable approach for development and deployment.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Webcam preview</title>
  <style>
    video { width: min(100%, 720px); background: #111; display: block; }
    button { margin: 0.75rem 0.5rem 0 0; }
  </style>
</head>
<body>
  <video id="preview" autoplay muted playsinline></video>
  <button id="start" type="button">Start camera</button>
  <button id="stop" type="button" disabled>Stop camera</button>
  <p id="status" role="status" aria-live="polite"></p>

  <script>
    const video = document.querySelector('#preview');
    const start = document.querySelector('#start');
    const stop = document.querySelector('#stop');
    const status = document.querySelector('#status');
    let stream;

    start.addEventListener('click', async () => {
      if (!navigator.mediaDevices?.getUserMedia) {
        status.textContent = 'Camera access requires a secure context (HTTPS or localhost).';
        return;
      }

      try {
        stream = await navigator.mediaDevices.getUserMedia({
          video: true,
          audio: false
        });
        video.srcObject = stream;
        await video.play();
        status.textContent = 'Camera preview is running.';
        start.disabled = true;
        stop.disabled = false;
      } catch (error) {
        status.textContent = `${error.name}: ${error.message}`;
      }
    });

    stop.addEventListener('click', () => {
      stream?.getTracks().forEach((track) => track.stop());
      video.srcObject = null;
      stream = undefined;
      start.disabled = false;
      stop.disabled = true;
      status.textContent = 'Camera stopped.';
    });

    window.addEventListener('pagehide', () => {
      stream?.getTracks().forEach((track) => track.stop());
    });
  </script>
</body>
</html>

getUserMedia() prompts for permission and resolves to a MediaStream. Assigning that stream to srcObject displays its live video track. The explicit await video.play() catches autoplay failures instead of leaving a silent, blank preview.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Logitech C270 720p Webcam Plug-and-Play Wide Screen Video Calling - Black
  • Compatible with Nintendo Switch 2’s new GameChat mode
  • Crisp HD 720p/30 fps video calls with diagonal 55° field of view and auto light correction. Compatible with popular platforms including Skype and Zoom.
  • The built-in noise-reducing mic makes sure your voice comes across clearly up to 1.5 meters away, even if you’re in busy surroundings.
  • C270’s RightLight 2 feature adjusts to lighting conditions, producing brighter, contrasted images to help you look good in all your conference calls.
  • The adjustable universal clip lets you attach the camera securely to your screen or laptop, or fold the clip and set the webcam on a shelf. You’re always ready for your next video call.

Requirements before the camera can work

Use a secure context

Camera capture is restricted to secure contexts. Use HTTPS in production; localhost is the usual development exception. If navigator.mediaDevices is undefined, inspect the page URL and browser security context before changing the JavaScript.

Ask at a clear moment

Permission should follow a visible Start button. Do not request a camera as soon as an unrelated page loads: users understand a prompt better when it follows an action. A denial must produce an explanation and a way to try again after changing browser permissions.

Request only what you need

For a webcam preview, use video: true, audio: false. Asking for audio unnecessarily creates a second permission decision and increases the privacy scope of the feature.

Embedded pages need delegation

An iframe may be blocked even when its own code is correct. The embedding document must delegate camera access with Permissions Policy and the iframe must include an appropriate allow="camera" attribute, for example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<iframe src="https://app.example.test/preview" allow="camera"></iframe>

The server’s Permissions-Policy response can further restrict which origins are allowed. A policy block commonly appears as NotAllowedError.

Rank #2
Sale
Logitech Brio 101 Full HD 1080p Webcam for Streaming and Meetings - Black
  • Compatible with Nintendo Switch 2’s new GameChat mode
  • Auto-Light Balance: RightLight boosts brightness by up to 50%, reducing shadows so you look your best—compared to previous-generation Logitech webcams (1)
  • Privacy with a Slide: The integrated webcam cover makes it easy to get total, reliable privacy when you're not on a video call
  • Built-In Mic: The built-in microphone lets others hear you clearly during video calls
  • Easy Plug-And-Play: The Brio 101 works with most video calling platforms, including Microsoft Teams, Zoom and Google Meet—no hassle; it just works

Why autoplay muted playsinline matters

autoplay lets the element begin rendering when the stream is attached. muted avoids an audible autoplay violation; it is appropriate because this example does not capture audio. playsinline keeps playback inside the page on mobile Safari and is required there for inline autoplay. JavaScript video.play() is still subject to autoplay policy, so always handle its rejected promise as the example does.

Choosing a camera and resolution

Start with a flexible request

{ video: true } lets the browser choose an available camera and a compatible mode. Treat width and height as preferences rather than guarantees:

const stream = await navigator.mediaDevices.getUserMedia({
  video: { width: 1280, height: 720 },
  audio: false
});

The actual result can differ. Inspect it with stream.getVideoTracks()[0].getSettings() and design the layout to accept other dimensions.

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

Add a camera picker only when needed

Call enumerateDevices() after permission, then populate a selector with devices whose kind is videoinput. Labels are often empty before permission is granted. Request the chosen camera by its ID:

const devices = await navigator.mediaDevices.enumerateDevices();
const cameras = devices.filter((device) => device.kind === 'videoinput');
const selected = cameras[0];
const stream = await navigator.mediaDevices.getUserMedia({
  video: { deviceId: { exact: selected.deviceId } },
  audio: false
});

Only use exact when the interface can recover from a camera disappearing or becoming busy. Otherwise use a preference such as deviceId: selected.deviceId and provide a fallback to video: true.

Rank #3
Xweiryn Webcam for PC, HD 1080P USB Plug-and-Play Computer Web Camera, High Definition Webcam for Desktop Laptop, Ideal for Online Class, Video Conference, Live Streaming & Gaming
  • 1080P HD Webcam: This HD webcam delivers crisp 1080p video quality, ideal for PCs, desktops, and laptops. Perfect for video calls, online classes, meetings, live streaming, gaming, and everyday recording. It provides clear, sharp images and smooth video at up to 30 frames per second. This live streaming webcam works with platforms such as Zoom, Teams, FaceTime, Google Meet, and YouTube.
  • USB Plug and Play Webcam: Designed for PCs, this webcam is easy to use. No drivers or software are required; simply connect the webcam to your computer and start using it immediately. Operation is smooth and convenient. XWEIRYN webcams are compatible with multiple operating systems, including Mac/Windows XP/7/8/10/11/PC/Laptops.
  • Widely Compatible Webcam: This versatile webcam is compatible with most operating systems and major video platforms. As a reliable computer webcam, it supports video conferencing, remote learning, live streaming, and gaming, meeting your various needs for daily work and entertainment.
  • Smooth and Stable Performance: This webcam uses a stable transmission chip to ensure smooth, lag-free video streaming, synchronized audio and video, and no dropped frames. Even after prolonged use, this durable webcam maintains stable performance. It performs excellently even in low-light environments. It automatically adjusts to adapt to low-light conditions, reducing noise and restoring vibrant colors, ensuring clear and sharp images even without additional studio lighting.
  • Compact and Adjustable Design: This lightweight and portable webcam saves space and comes with an adjustable clip. Our USB webcam uses a reliable USB 2.0/3.0 connection and comes with an upgraded 1.5-meter (5-foot) braided cable. It is compatible with Desktop most monitors and Laptop. Its portable design makes it easy to place and carry, ideal for home, office, or travel use.

Relax impossible constraints

High resolutions, a particular facing mode, or an exact device can fail on older hardware. Begin with flexible constraints, then progressively request more. Do not assume a nominal 1280×720 camera can deliver that mode under every operating-system or browser condition.

Stopping safely and protecting privacy

Clearing the element is not enough: call stop() on every track. Otherwise the camera may remain active, the browser indicator may stay lit, and another application may be unable to use the device. Stop when the user clicks Stop, leaves the feature, navigates away, or your component unmounts. Keep the camera indicator visible in your UI and explain that the browser also provides its own indicator.

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

If the user starts again after stopping, request a new stream rather than reusing stopped tracks. Do not store or upload frames unless that is a separate, clearly disclosed feature.

How do I preview my webcam in the browser when it fails?

NotAllowedError

The user denied access, the page is not secure, or an iframe Permissions Policy blocks the request. Tell the user to use HTTPS, allow the camera for this site in browser settings, and check the iframe’s allow attribute and response policy. A previous denial may require changing the permission from the browser’s address-bar controls.

NotFoundError

No camera satisfies the request. Confirm that a camera is connected and enabled, then retry with video: true instead of a restrictive device, resolution, or facing-mode constraint.

Rank #4
Sale
EMEET C960 1080P Webcam with Microphone, 2 Mics, 90° FOV, Computer Camera
  • 1080P Webcam with Cover for Video Calls - EMEET computer webcam provides design and Optimization for professional video streaming. Realistic 1920 x 1080p video, 5-layer anti-glare lens, providing smooth video. C960 computer camera delivers 1920x1080 video with fixed focus (11.8–118.1 inches), so as to provide a clearer image. C960 USB webcam has a cover and can be removed automatically to meet your needs for privacy. For optimal image performance, use the webcam in a well-lit environment.
  • Built-in 2 Omnidirectional Mics - EMEET webcam with microphone for desktop features 2 built-in omnidirectional microphones, picking up your voice to create clear audio for communication. When installing the webcam, select EMEET C960 as the default microphone input device in your computer and video applications and select C960 as the default device in Zoom/Teams and ensure microphone permissions are enabled for proper use. Please note that C960 does not include built-in speakers.
  • Automatic Light Adjustment - Automatic exposure adjustment is applied in EMEET HD webcam 1080p so that the streaming webcam can deliver stable image performance. EMEET C960 camera for computer also features color adjustment and exposure optimization to help you look your best. For optimal video quality, it is recommended to use the webcam in normal or well-lit environments and select suitable video settings in your application. Proper lighting helps achieve a clearer and more balanced image.
  • Plug-and-Play & Upgraded USB Connectivity - New C960 webcam features both USB Type-A & A-to-C adapter connections for wider compatibility. For stable performance, connect the webcam directly to the computer's main USB port and ensure the device is recognized correctly. If a hub or docking station is used, please ensure it provides sufficient power and stable data transmission, as limited ports may affect performance. 90° wide-angle lens captures more participants without frequent adjustments.
  • High Compatibility & Multi Application - C960 webcam for laptop is compatible with Windows 10/11, macOS 10.14+, and Android TV 7.0+. Not supported: Windows Hello, TVs, tablets, or game consoles. It works with Zoom, Teams, Facetime, Google Meet, YouTube and more. Please select C960 webcam as the default camera and microphone device in your application and ensure camera/microphone permissions are enabled, especially on macOS. (Tips: Incompatible with Windows Hello)

NotReadableError

Permission was granted but the operating system, hardware, or another application could not provide frames. Close conferencing or recording apps, check the operating-system privacy setting, reconnect the USB camera, and retry.

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.

OverconstrainedError

The requested constraints cannot be met. Inspect error.constraint, remove exact requirements, lower the requested resolution, or return to the default camera request.

TypeError or missing mediaDevices

An empty or false constraint object is invalid, and insecure contexts can make the API unavailable. Verify that the request includes video, that the page is HTTPS or localhost, and that the browser is not running in an unsupported embedded context.

The video element stays blank

Check that video.srcObject = stream runs after the promise resolves, that the stream has a live video track, and that await video.play() is not rejected. Keep muted and playsinline, and look for a browser console autoplay error.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Browser support and legacy code

The promise-based navigator.mediaDevices.getUserMedia() API is the correct interface for new code and has broad browser availability. The callback-style navigator.getUserMedia() is deprecated; do not build a new preview around it. Permission prompts, device labels, autoplay rules, and camera selection can still differ by browser and device, so test the actual combinations your product supports.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

Production checklist

  • Serve the feature over HTTPS, with localhost reserved for development.
  • Trigger permission from a clearly labeled user action.
  • Request video only unless microphone capture is required.
  • Use autoplay muted playsinline and handle the play() promise.
  • Show specific recovery text for permission, missing-device, hardware, and constraint errors.
  • Stop every track and clear srcObject on exit.
  • Test top-level pages and iframe deployments separately.
  • Verify behavior with no camera, a busy camera, multiple cameras, and a disconnected camera.

Or skip the browser setup

ScreenshotNeo is a website screenshot API, not a webcam-capture API. If your goal is to capture a rendered page that contains your preview UI, it can remove the browser automation setup. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

One GET request returns an image or PDF. See the ScreenshotNeo documentation for all options:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it.

Frequently Asked Questions

Can I preview a webcam without showing a video element?

You can read frames from a video element by drawing them to a canvas, but the video element remains the simplest and most compatible way to render a live MediaStream.

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

Does getUserMedia work from a plain HTTP website?

Normally no. Use HTTPS; localhost is the standard secure development exception.

Why are camera names missing from enumerateDevices()?

Browsers commonly hide device labels until the user has granted permission. Enumerate devices after a successful camera request.

Can I request the front or rear camera on a phone?

Use a facingMode preference such as environment or user, but treat it as a preference and provide fallback handling because hardware and browser behavior vary.

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.