Support0

HTML <usermedia> playground

Explore <usermedia> as a trusted, browser-managed control for requesting camera and microphone access. Configure setConstraints(), connect the MediaStream to a preview, and compare the native element with progressive enhancement based on getUserMedia().

Ask AI

HTML <usermedia> playground

Response generated with openai/gpt-5.4-nano. AI can make mistakes. Always review the result.
Checking support…

Camera and microphone

The preview will appear here after you grant camera access.

Activate the control to request camera and microphone access.

HTML
<section class="usermedia-demo" aria-labelledby="usermedia-title">
  <h2 id="usermedia-title">Camera and microphone</h2>

  <div class="stream-preview">
    <video
      id="media-preview"
      autoplay
      playsinline
      muted
      hidden
      aria-label="Camera preview"
    ></video>
    <p data-media-placeholder>The preview will appear here after you grant camera access.</p>
  </div>

  <div class="media-actions">
    <usermedia id="media-control" aria-describedby="media-status">
      <button type="button" id="fallback-media-control">
        Enable camera and microphone
      </button>
    </usermedia>
    <button type="button" id="stop-media" disabled>
      Stop capture
    </button>
  </div>

  <p id="media-status" role="status" aria-live="polite">
    Activate the control to request camera and microphone access.
  </p>
</section>
JS
const mediaControl = document.querySelector('#media-control');
const fallbackButton = document.querySelector('#fallback-media-control');
const videoPreview = document.querySelector('#media-preview');
const placeholder = document.querySelector('[data-media-placeholder]');
const stopButton = document.querySelector('#stop-media');
const status = document.querySelector('#media-status');

const constraints = {
  video: {
    width: 1280,
    height: 720,
    facingMode: "user",
    frameRate: 30,
  },
  audio: {
    echoCancellation: true,
    noiseSuppression: true,
    autoGainControl: true,
  },
};
let currentStream = null;

const showStatus = (message) => {
  status.textContent = message;
};

const attachStream = (stream) => {
  if (!stream) return;

  currentStream = stream;
  videoPreview.srcObject = stream;
  videoPreview.hidden = false;
  placeholder.hidden = true;
  stopButton.disabled = false;
  showStatus("Capture is active. Video is muted to prevent feedback.");
};

const stopStream = () => {
  currentStream?.getTracks().forEach((track) => track.stop());
  currentStream = null;
  videoPreview.srcObject = null;
  videoPreview.hidden = true;
  placeholder.hidden = false;
  stopButton.disabled = true;
  showStatus("Capture has stopped.");
};

if ('HTMLUserMediaElement' in window) {
  mediaControl.setConstraints(constraints);

  mediaControl.addEventListener('stream', () => {
    attachStream(mediaControl.stream);
  });

  mediaControl.addEventListener('error', () => {
    const errorName = mediaControl.error?.name ?? 'UnknownError';
    showStatus(`Capture could not start: ${errorName}.`);
  });

  mediaControl.addEventListener('cancel', () => {
    showStatus("The permission request was cancelled.");
  });
} else {
  fallbackButton.addEventListener('click', async () => {
    if (!navigator.mediaDevices?.getUserMedia) {
      showStatus("Media capture is unavailable in this context or browser.");
      return;
    }

    showStatus("Waiting for the browser…");

    try {
      attachStream(await navigator.mediaDevices.getUserMedia(constraints));
    } catch (error) {
      const errorName = error instanceof DOMException ? error.name : 'UnknownError';
      showStatus(`Capture could not start: ${errorName}.`);
    }
  });
}

stopButton.addEventListener('click', stopStream);

Educational guide to usermedia

From capture intent to a stream you control

Distinguish <usermedia> from getUserMedia(), configure preferences, and connect tracks to a preview. Learn to handle permissions, errors, and capture cleanup with a progressive fallback.

Mental model

The control requests access; the stream provides tracks; your application decides how to use and release them.

  1. Activation · intent

    A person activates a visible control and the browser handles consent and acquisition.

  2. MediaStream · tracks

    The stream event lets you read the element’s stream property and connect audio and video to the application.

  3. stop() · release

    The application stops each track when it no longer needs it and removes the preview reference.

Action → consent → tracks → cleanupStatic diagram: it does not represent a connected camera or granted permission. This guide’s code examples do not run; the real test is in the playground.

A stream is not a recording or a network connection. It groups media tracks you can display, process, record with another API, or send through an explicit connection. Assigning it to video.srcObject only connects that source to the local player.

Native element versus imperative API

They share a result type, but differ in who initiates and presents the request.

<usermedia> offers a browser-managed control to acquire camera and microphone together. Configure setConstraints() and listen for stream, error, and cancel. When stream fires, read element.stream: the event is not the MediaStream object, and you should not start an additional getUserMedia() call.

getUserMedia() returns a Promise and leaves the button, states, and failure handling to your application. It is the alternative for browsers without the element and for audio-only or video-only capture. Do not transfer audio: false or video: false to the <usermedia> contract: its audio/video options are dictionaries, and the element covers both tracks.

Child text belongs to the fallback; it does not control the native button label, which the browser chooses. Avoid treating this trusted control as an arbitrary button: the browser may restrict styling, size, contrast, or occlusion and disable a presentation it considers invalid.

Permissions and execution context

Support, granted permission, and an available device are separate conditions.

Serve capture from a secure context, usually HTTPS; localhost enables local development. Explain the purpose before requesting access and tie the fallback to an explicit action. These recipes omit autostart and do not call getUserMedia() on load. Configuring preferences does not start capture.

In an iframe, check the camera and microphone Permissions Policy directives, delegation from the parent document, and relevant allow/sandbox attributes. An allow cannot override a stricter header or grant permission on someone’s behalf. Browser or operating-system restrictions and a busy device can also prevent capture.

Denial is not solved by requesting access in a loop. Offer instructions to review site and system permissions, keep the rest of the interface usable, and let people choose to retry. Detecting HTMLUserMediaElement does not confirm that the next capture will succeed.

Progressive camera and microphone recipe

A local preview, a stop action, and two paths to the same stream type.

This recipe reuses the playground’s HTML and JavaScript with its initial configuration. A supporting browser shows the native control; otherwise, activating the child button calls getUserMedia(). Copy both blocks and load JavaScript after the HTML, for example as a module. Decorative CSS is unnecessary.

Combined capture with a fallback and explicit stop

Combined capture with a fallback and explicit stop
<section class="usermedia-demo" aria-labelledby="usermedia-title">
  <h2 id="usermedia-title">Camera and microphone</h2>

  <div class="stream-preview">
    <video
      id="media-preview"
      autoplay
      playsinline
      muted
      hidden
      aria-label="Camera preview"
    ></video>
    <p data-media-placeholder>The preview will appear here after you grant camera access.</p>
  </div>

  <div class="media-actions">
    <usermedia id="media-control" aria-describedby="media-status">
      <button type="button" id="fallback-media-control">
        Enable camera and microphone
      </button>
    </usermedia>
    <button type="button" id="stop-media" disabled>
      Stop capture
    </button>
  </div>

  <p id="media-status" role="status" aria-live="polite">
    Activate the control to request camera and microphone access.
  </p>
</section>
const mediaControl = document.querySelector('#media-control');
const fallbackButton = document.querySelector('#fallback-media-control');
const videoPreview = document.querySelector('#media-preview');
const placeholder = document.querySelector('[data-media-placeholder]');
const stopButton = document.querySelector('#stop-media');
const status = document.querySelector('#media-status');

const constraints = {
  video: {
    width: 1280,
    height: 720,
    facingMode: "user",
    frameRate: 30,
  },
  audio: {
    echoCancellation: true,
    noiseSuppression: true,
    autoGainControl: true,
  },
};
let currentStream = null;

const showStatus = (message) => {
  status.textContent = message;
};

const attachStream = (stream) => {
  if (!stream) return;

  currentStream = stream;
  videoPreview.srcObject = stream;
  videoPreview.hidden = false;
  placeholder.hidden = true;
  stopButton.disabled = false;
  showStatus("Capture is active. Video is muted to prevent feedback.");
};

const stopStream = () => {
  currentStream?.getTracks().forEach((track) => track.stop());
  currentStream = null;
  videoPreview.srcObject = null;
  videoPreview.hidden = true;
  placeholder.hidden = false;
  stopButton.disabled = true;
  showStatus("Capture has stopped.");
};

if ('HTMLUserMediaElement' in window) {
  mediaControl.setConstraints(constraints);

  mediaControl.addEventListener('stream', () => {
    attachStream(mediaControl.stream);
  });

  mediaControl.addEventListener('error', () => {
    const errorName = mediaControl.error?.name ?? 'UnknownError';
    showStatus(`Capture could not start: ${errorName}.`);
  });

  mediaControl.addEventListener('cancel', () => {
    showStatus("The permission request was cancelled.");
  });
} else {
  fallbackButton.addEventListener('click', async () => {
    if (!navigator.mediaDevices?.getUserMedia) {
      showStatus("Media capture is unavailable in this context or browser.");
      return;
    }

    showStatus("Waiting for the browser…");

    try {
      attachStream(await navigator.mediaDevices.getUserMedia(constraints));
    } catch (error) {
      const errorName = error instanceof DOMException ? error.name : 'UnknownError';
      showStatus(`Capture could not start: ${errorName}.`);
    }
  });
}

stopButton.addEventListener('click', stopStream);

muted prevents local microphone playback, but does not disable it: the stream retains its audio track. playsinline helps keep video playback inline. Neither permission nor autoplay guarantees playback in every environment; check real behaviour. This recipe is a starting point: an integration must also handle pending requests, stream replacement, and unmounting.

Preferences, requirements, and actual settings

Requesting HD does not prove the camera delivers HD, and constraint contracts are not identical.

In the recipe, width, height, facingMode, and frameRate are preferences, subject to the device and browser. Configure setConstraints() before interaction. The element proposal filters required constraints; do not assume exact, min, max, or advanced transfer as they do with getUserMedia(). setConstraints() does not modify a track that is already capturing either.

Shared preferences and a getUserMedia()-only requirement

Shared preferences and a getUserMedia()-only requirement
JavaScript
const preferences = {
  "video": {
    "width": 1280,
    "height": 720,
    "facingMode": "user",
    "frameRate": 30
  },
  "audio": {
    "echoCancellation": true,
    "noiseSuppression": true,
    "autoGainControl": true
  }
};

const getUserMediaRequirements = {
  audio: true,
  video: {
    width: { min: 1280 },
    height: { ideal: 720 },
  },
};

The second object illustrates an imperative API requirement: demanding a minimum width of 1280 pixels can cause OverconstrainedError before a prompt. No request runs here. In getUserMedia(), ideal or a plain value expresses a preference; min, max, and exact impose requirements. Do not mistake that error for permission denial.

After acquisition, read track.getSettings() for each track’s actual settings. getSupportedConstraints() identifies keys the browser understands, not the capabilities of a particular camera. To renegotiate a track, use applyConstraints(), handle rejection, and read getSettings() again; a preset does not promise an exact resolution, camera, or audio processing configuration.

Stopping capture and handling late responses

A microphone-only check demonstrates the lifecycle without requesting a camera or playing back your voice.

This independent recipe uses getUserMedia({ audio: true, video: false }) to check the microphone. It blocks duplicate activation, lets you stop a pending request, and releases a stream that arrives after that stop. State changes are announced with role="status" without moving focus.

Microphone with stop, page exit, and late-response handling

Microphone with stop, page exit, and late-response handling
<button type="button" data-mic-start aria-describedby="mic-check-status">
  Check microphone
</button>
<button type="button" data-mic-stop disabled>
  Stop check
</button>
<p id="mic-check-status" data-mic-status role="status">
  Microphone inactive. Audio is not recorded or played back.
</p>
const startButton = document.querySelector('[data-mic-start]');
const stopButton = document.querySelector('[data-mic-stop]');
const status = document.querySelector('[data-mic-status]');
let currentStream = null;
let generation = 0;

const stop = () => {
  generation += 1;
  currentStream?.getTracks().forEach((track) => track.stop());
  currentStream = null;
  startButton.disabled = false;
  stopButton.disabled = true;
  status.textContent = "Check stopped.";
};

startButton.addEventListener('click', async () => {
  if (startButton.disabled) return;

  if (!navigator.mediaDevices?.getUserMedia) {
    status.textContent = "Capture is unavailable. Check the secure context and browser.";
    return;
  }

  const request = ++generation;
  startButton.disabled = true;
  stopButton.disabled = false;
  status.textContent = "Waiting for microphone access…";

  try {
    const stream = await navigator.mediaDevices.getUserMedia({
      audio: true,
      video: false,
    });

    if (request !== generation) {
      stream.getTracks().forEach((track) => track.stop());
      return;
    }

    currentStream = stream;
    status.textContent = "Microphone active. Audio is not recorded or played back.";
    stream.getTracks().forEach((track) => {
      track.addEventListener('ended', () => {
        if (currentStream === stream) stop();
      }, { once: true });
    });
  } catch (error) {
    if (request !== generation) return;

    stop();
    const name = error instanceof DOMException ? error.name : 'UnknownError';
    status.textContent = "Could not start the microphone. Review the permission or device diagnosis:" + ' ' + name;
  }
});

stopButton.addEventListener('click', stop);
window.addEventListener('pagehide', stop);

Stop does not close the prompt or cancel the Promise: it invalidates the response and stops its tracks if they arrive later. A request can remain pending if someone ignores it. Also call cleanup when unmounting a SPA view; pagehide covers leaving the page, not every internal navigation.

video.pause(), video.hidden, or srcObject = null do not stop tracks. Call stop() on every track your flow owns and clear references. stop() sets readyState to ended without firing ended: update the interface directly. The ended event handles external endings such as revocation. Stopping a track does not revoke permission, and other tracks or tabs may still use the device.

Common mistakes

Identify the failing stage before changing constraints or requesting access again.

NotAllowedError or cancel when requesting access

Expected result
People can decline capture and understand how to continue.
Cause
Denied permission, a dismissed request, or context, policy, or system restrictions. The element’s cancel and Promise rejection are different contracts.
Solution
Listen for cancel and error on the element; catch getUserMedia() rejection. Review HTTPS, policies, and permissions, explain recovery, and wait for an explicit retry.

NotFoundError or NotReadableError

Expected result
The interface explains that the requested device was not acquired.
Cause
No input of the requested type exists, or the browser/system cannot open it even though permission was granted.
Solution
Check connections, system permissions, and applications using the device. Request only necessary track types; avoid automatic retries without diagnosis.

Resolution differs or OverconstrainedError occurs

Expected result
The interface distinguishes a preference from an impossible requirement.
Cause
A preset was treated as a guarantee, or getUserMedia()/applyConstraints() received required constraints that cannot be satisfied.
Solution
Read getSettings(), use preferences when sufficient, and relax imperative API requirements when your use case allows it. Do not assume setConstraints() preserves those restrictions.

Capture continues after hiding the video

Expected result
All owned tracks are released when capture ends, is replaced, or is unmounted.
Cause
Only the player was hidden, a previous stream reference was lost, or a pending request completed after stopping.
Solution
Keep the stream, stop each track, and clear srcObject. Guard late responses and update state without waiting for an ended event caused by stop().

Support and compatibility

Separate the element, the capture API, and device capabilities.

As checked on 22 October 2026, Chrome documents <usermedia> from version 151. MDN BCD records that addition and no Firefox or Safari support; the element remains experimental and has limited availability. Its draft can evolve: a proposal does not imply interoperable support.

getUserMedia() and MediaStreamTrack.stop() are widely available. This does not guarantee permission, hardware, playback, or every constraint. Detect the element, keep the fallback button, and also check navigator.mediaDevices?.getUserMedia; if it is absent, show an explanation rather than pretending to capture.

Verify keyboard, focus, zoom, screen readers, and real devices for both the native control and fallback. The guide does not simulate granted permission or test hardware for you; use the playground only when you intend to start real capture.