12k
All articles

Accessing the Camera with the HTML usermedia Element

Explore the HTML usermedia element for camera and microphone access, including constraints, events, Chrome support, denial recovery, and a getUserMedia fallback.

OpenReplay Team
OpenReplay Team
Accessing the Camera with the HTML usermedia Element

The <usermedia> element is a browser-drawn button that asks for camera and microphone access when the user clicks it, then hands your page the resulting MediaStream through its read-only stream property.

When a user blocks the camera once and then can’t find their way back, a single misclick ends up as a support ticket. That denial-recovery problem is what this element targets. This guide covers the markup, constraints, events, a complete getUserMedia() fallback, and whether it’s worth adopting yet.

Key Takeaways

  • <usermedia> is available from Chrome 151 and fires stream, error, and cancel events instead of returning a promise.
  • Browsers without support render the element’s children, so a <button> inside it can act as the getUserMedia() fallback trigger.
  • Detect support with 'HTMLUserMediaElement' in window, because unsupported browsers still parse the tag into the DOM.
  • In third-party testing, only the first setConstraints() call took effect and range objects such as { ideal: 1280 } were dropped.
  • No browser vendor other than Chrome has published a position on <usermedia>, so a working fallback is mandatory.

What Does the usermedia Element Do?

<usermedia> hands the whole camera and microphone permission flow to the browser: the button, the prompt, and the path back after a denial. If a user previously blocked access, clicking the element starts a recovery flow inside the page, so they don’t have to dig through browser settings.

It follows the same declarative pattern as the <geolocation> element. Chrome’s announcement places <usermedia> next in the Capability Elements suite after <geolocation> shipped in Chrome 144. In Chrome’s origin trial, Zoom reported a “46.9% decrease in camera or microphone capture errors”. That figure comes from Zoom, as reported by Google.

Basic Markup with a Fallback Button

The <usermedia> element wraps fallback content. Chrome renders its own control. Other browsers treat the tag as an HTMLUnknownElement and render its children, so the <button> inside becomes the trigger for the getUserMedia() fallback.

<usermedia id="cam-ctrl">
  <button id="cam-fallback">Turn on camera</button>
</usermedia>

<video id="preview" autoplay muted playsinline></video>
<p id="status" role="status"></p>

The <video> is muted because the stream includes audio, and playing it back unmuted would cause feedback.

Setting Constraints with setConstraints()

On a <usermedia> element, setConstraints() takes a { video, audio } dictionary and must be called before the user clicks. The Media Capture Extensions draft runs stored constraints through a constraint filter before the request is made. Call it once, with plain values and everything you need.

const constraints = {
  video: { width: 1280, height: 720 },
  audio: { echoCancellation: true },
};

Gotchas From Third-Party Testing

Addpipe’s hands-on demo reported these behaviours. Chrome’s announcement doesn’t document them.

  • Only the first setConstraints() call took effect.
  • { ideal } and other range objects were dropped silently.
  • A script-triggered click() failed, and only a real user click worked.
  • The element required HTTPS or localhost. The spec draft confirms that in a non-secure context it shows its fallback content.
  • Adding a type attribute switched it back to legacy <permission> mode.

Chrome’s own post adds one more limitation: <usermedia> requests audio and video together.

Handling the stream, error, and cancel Events

The element reports success with a stream event and exposes the result as a read-only MediaStream on element.stream. Failures fire error, with details in element.error as a DOMException. A dismissed prompt fires a separate cancel event.

const ctrl = document.getElementById('cam-ctrl');
const preview = document.getElementById('preview');
const statusEl = document.getElementById('status');

function handleStream(stream) {
  preview.srcObject = stream;
  statusEl.textContent = '';
}

function showError(err) {
  switch (err?.name) {
    case 'NotAllowedError':
      statusEl.textContent = 'Camera access was blocked. Allow it to continue.';
      break;
    case 'NotFoundError':
      statusEl.textContent = 'No camera or microphone found.';
      break;
    default:
      statusEl.textContent = `Could not start camera (${err?.name ?? 'unknown error'}).`;
  }
}

handleStream() always receives a MediaStream and never an event object, so both code paths can share it.

Feature Detection and the getUserMedia Fallback

Detect support with 'HTMLUserMediaElement' in window. Checking for the tag doesn’t work, because every browser parses it into the DOM. Without support, wire the inner button to navigator.mediaDevices.getUserMedia(). It rejects with NotAllowedError when the user denies access and with NotFoundError when no matching device exists.

const fallbackBtn = document.getElementById('cam-fallback');

if ('HTMLUserMediaElement' in window) {
  ctrl.setConstraints(constraints);
  ctrl.addEventListener('stream', () => handleStream(ctrl.stream));
  ctrl.addEventListener('error', () => showError(ctrl.error));
  ctrl.addEventListener('cancel', () => {
    statusEl.textContent = 'Camera request dismissed.';
  });
} else {
  fallbackBtn.addEventListener('click', () => {
    navigator.mediaDevices
      .getUserMedia(constraints)
      .then(handleStream)
      .catch(showError);
  });
}

Both branches use the same showError(), so a denial produces the same message on either path. When you are done, release the camera with stream.getTracks().forEach((t) => t.stop()).

How Is usermedia Different From getUserMedia?

<usermedia> doesn’t replace getUserMedia(). It moves the trigger and the recovery flow into browser UI, and the stream underneath is the same. With getUserMedia(), your script decides when the prompt appears. With <usermedia>, the prompt appears only after a real click on a control the browser renders.

AspectgetUserMedia()<usermedia>
Prompt triggerAny script callTrusted user click (Chrome post)
Recovery after denialSite sends user to settingsIn-page recovery flow (Chrome post)
ConstraintsFull syntax, including ideal/exactFiltered; bare values only (observed by Addpipe)
Media requestedAudio, video, or bothAudio and video together (Chrome post)
StylingYour own button3:1 contrast, opacity 1, size bounds, 2D transforms only (Chrome post)
SupportAll modern browsersChrome 151+

A stuck user shows up in neither path’s logs. MDN notes that the getUserMedia() promise may never settle if the prompt is ignored. In a session replay, a user stuck after denying camera access looks like repeated clicks on the enable-camera button with no preview ever appearing. That is the scenario this element targets.

Migrating from permission and Browser Support

<usermedia> ships in Chrome 151 and later. Chromium’s Intent to Ship excludes Android WebView, and no other browser vendor has published a position. Origin-trial code needs two changes: replace <permission type="camera microphone"> with <usermedia>, and update the feature check.

<!-- Before -->
<permission type="camera microphone"></permission>
<script>
  if ('HTMLPermissionElement' in window) { /* ... */ }
</script>

<!-- After -->
<usermedia></usermedia>
<script>
  if ('HTMLUserMediaElement' in window) { /* ... */ }
</script>

Also update any CSS selectors that target permission. Chrome 153 added single-capability <camera> and <microphone> elements that use the same security model and recovery path.

Before adopting <usermedia>, check these points:

  • It works only in Chrome, so you still need the fallback above.
  • A voice-input feature built on <usermedia> also requests the camera. Look at <microphone> for that case.
  • Its value is highest where users denying the permission and getting stuck is your main support problem.
  • React apps that need consistent behaviour across browsers can use a library such as react-webcam.

Conclusion

<usermedia> is a progressive enhancement. It adds a browser-owned recovery path in Chrome and falls back to the getUserMedia() code you already have everywhere else. Put the element around your existing camera button, route both paths through one handleStream() and one showError(), and test over HTTPS with a real click before rolling it out.

FAQs

How do I style the usermedia element differently once camera access is granted?

Use the :granted pseudo-class. Chrome documents that usermedia:granted matches once permission is active and the stream has been acquired, and the element also supports standard interaction states such as :hover and :active. Any styles you apply in these states must still follow the element's rules: 3:1 contrast, opacity 1, size bounds, and only 2D translate or proportional scale transforms.

Why does clicking the usermedia element do nothing, with no error event?

The element is probably in an invalid state. In Addpipe's testing, a usermedia element that is blocked by Permissions Policy, covered by another element, or styled outside Chrome's rules ignores clicks and fires no stream, error, or cancel event. Check contrast, opacity, size, and overlapping elements first. Then confirm the page runs over HTTPS or localhost and that the click comes from a real user.

Does the usermedia element work inside an iframe?

Yes, but the frame needs permission. The element follows the same Permissions Policy as getUserMedia(), so a cross-origin iframe needs the camera and microphone features delegated, for example with allow='camera; microphone'. Addpipe's testing also found that the frame must be allowed by a CSP frame-ancestors directive, otherwise the element is invalid in any frame cross-origin to the top-level page.

Can usermedia restart a previously granted camera stream on page load without a click?

No. In Addpipe's testing, Chrome 151 offers no way for the element to resume a previously granted stream without a fresh user click, although the W3C explainer discusses the idea. If your app must start the camera automatically for returning users who already granted permission, call getUserMedia() on load and keep usermedia for the first request and for recovery after a denial.

Open-source session replay

Complete picture for complete understanding

Capture every clue your frontend is leaving so you can instantly get to the root cause of any issue with OpenReplay — the open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data.

Star on GitHub12k

We use cookies to improve your experience. By using our site, you accept cookies.