`` HTML 元素
The HTML Element

原始链接: https://developer.chrome.com/blog/usermedia-html-element

从 Chrome 151 版本开始,全新的 `` HTML 元素将取代传统的由脚本触发的摄像头和麦克风访问权限请求。作为浏览器“能力元素”(Capability Elements)套件的一部分,这种声明式控制确保权限提示与用户明确发起的行为相关联,从而提升了安全性和用户体验。 通过摆脱命令式的 `getUserMedia()` 调用,`` 元素具有以下优势: * **减少样板代码**:它简化了实现过程,自动处理了从意图、权限提示到媒体流交付的流程。 * **更高的成功率**:实际测试(如 Cisco、Zoom 和 Google Meet)显示,用户授予权限的比率显著提高,且此前曾拒绝访问的用户能够更容易地恢复权限,有效消除了设置难以调整的“权限死角”。 * **增强的安全性**:浏览器强制执行的样式限制确保了权限触发机制的可读性和透明度,防止了欺骗性的 UI 模式。 该元素专为渐进增强设计,允许开发者利用特性检测,为不支持的浏览器实现向后兼容的传统 API 回退。此次转型标志着浏览器正向更专业的、以硬件为中心的 HTML 元素转变,为基于网络的媒体体验提供更直观、更可信的接口。

这篇 Hacker News 帖子讨论了引入一种新的 HTML `` 元素,旨在通过专门的用户交互按钮来管理摄像头和麦克风权限。 批评者认为该元素是 HTML 标准中不必要的补充,并指出通过用户操作要求即可实现的现有 JavaScript API 就能达到同样的目的。怀疑论者担心它会被用于“黑暗模式”,即通过欺骗性标签(例如“点击获取免费内容”)诱导用户授予他们本可能拒绝的权限。一些评论者指出,数据表明使用这一新元素后权限授予率显著增加,反对者认为这是在“诱骗”用户,而非改善用户体验。 许多参与者对谷歌倾向于实施缺乏广泛跨浏览器共识的 Chrome 特定标准表示不满,并将其与互联网探索者(IE)时代的“拥抱、扩展、熄灭”策略相提并论。该提案的捍卫者则认为,与当前的脚本方法相比,该元素在浏览器层面提供了更好的防点击劫持和“权限垃圾邮件”保护。尽管该功能目前以 Chrome 为中心,但一些人指出,W3C 的成员(包括 Firefox 的贡献者)也参与了更广泛的标准化进程。
相关文章

原文

Published: June 29, 2026

Following the launch of the <geolocation> element in Chrome 144, the next functional control in the Capability Elements suite is the <usermedia> HTML element. Available from Chrome 151, this element marks the next phase of the transition from generic permission requests to targeted and functional controls for accessing camera and microphone streams. By moving away from script-triggered prompts toward a declarative and user-activated experience, <usermedia> reduces boilerplate code, improves security, and provides a seamless recovery path for users who have previously denied access, effectively solving the long-standing permission hole.

From permission management to capability control

The <usermedia> element is the next specialized control to launch in the Capability Elements suite, following the successful introduction of <geolocation>. This transition from the original and generic <permission> proposal—part of the PEPC initiative—lets the browser handle the unique complexities and behaviors of different hardware capabilities more effectively. While the early proposal focused primarily on managing permission states, such as allow versus deny, Capability Elements function as data mediators.

The <geolocation> element provides a location object to your site, and <usermedia> manages the entire flow for camera and microphone access. It captures user intent, manages the browser prompt, and delivers the MediaStream object to the application. This shift eliminates the need for separate getUserMedia() calls, simplifies implementation, and ensures the browser has a trusted signal of the user's intent.

Validation of the concept

Real-world data from the initial Origin Trial demonstrated that the in-context and user-initiated permission controls significantly improve user success rates.

  • Cisco observed that users who initially denied permissions were only about 10% likely to successfully grant permissions using legacy prompts, but that rate jumped to more than 65% with the new element.
  • Zoom reported a 46.9% decrease in camera or microphone capture errors, such as system-level blockers, by using the element to guide users through recovery;
  • Google Meet saw a 17% decrease in "mic not working" feedback and a 131% increase in successful permission recovery for users who had initially denied access.

Building on the patterns established by <geolocation>, the <usermedia> element addresses the core challenges of requesting powerful capabilities. Media requests rely on imperative JavaScript calls that often trigger out-of-context prompts. If you accidentally block your site, reversing that decision requires navigating deep into browser settings, a "permission hole" that often leads to abandoned features.

The <usermedia> element solves these issues by providing the following:

  • Clear intent and timing: Because the prompt only appears after a physical tap on a browser-controlled element, it provides a trusted signal of intent. This lets the browser bypass automated quiet blocks that often cause typical script-triggered requests to fail.
  • Simplified recovery: If access was previously denied, tapping the element triggers a specialized recovery flow that lets you re-enable your camera or microphone instantly on the page, without navigating complex browser settings.
  • Direct stream access: As a data mediator, the element exposes the media stream directly. This reduces the boilerplate code required to manage callbacks and error states in your application.

Implementation

Integrating the element requires significantly less boilerplate than the legacy JavaScript API. Following the declarative pattern established by the <geolocation> element, you can add the <usermedia> tag to your HTML and configure hardware requirements with the setConstraints() method.

<usermedia id="media-ctrl">
  <button>Enable camera and microphone</button>
</usermedia>
const el = document.getElementById('media-ctrl');

// Specify hardware preferences before user interaction:
el.setConstraints({
    video: { width: 1280, height: 720 },
    audio: { echoCancellation: true }
});

// Handle successful stream acquisition:
el.addEventListener('stream', () => {
  videoPreview.srcObject = el.stream;
});

// Handle stream acquisition failure:
el.addEventListener('error', () => {
  console.error(`Access failed: ${el.error?.name}`);
});

// Handle prompt cancellation or dismissal:
el.addEventListener('cancel', () => {
  console.log('Permission prompt was dismissed by the user.');
});

Key attributes and properties

  • stream: A read-only property that provides the MediaStream object once the user has successfully granted access.
  • setConstraints(): A method that lets developers update hardware preferences, such as deviceId or resolution, prior to user interaction.
  • error: A read-only property that returns a DOMException (for example, a NotAllowedError) if the request fails or is dismissed.
  • onstream: An event handler that fires immediately once the media tracks are acquired.
  • onerror: An event handler that fires when a stream acquisition attempt fails.
  • oncancel: An event handler that fires when the user cancels or dismisses the permission prompt during acquisition.

Styling constraints

To ensure user trust and prevent deceptive design patterns, the <usermedia> element applies the same strict styling restrictions as other Capability Elements:

  • Legibility: The browser checks text and background colors for sufficient contrast (at least 3:1) to ensure the request is always readable. You must set the alpha channel (opacity) to 1 to prevent the element from being deceptively transparent.
  • Sizing and spacing: The browser enforces minimum and maximum bounds for width, height, and font-size. It disables negative margins or outline offsets to prevent the element from being visually obscured.
  • Visual integrity: The browser limits distorting effects. For example, transform supports only 2D translations and proportional scaling.
  • CSS pseudo-classes: The element supports state-based styling, such as :granted (which activates once permission is active and the stream is acquired), as well as standard interaction states like :hover and :active.

Progressive enhancement and migration strategy

Following the design pattern established by <geolocation>, the <usermedia> element is built to degrade gracefully. Browsers that don't support the element will treat it as an HTMLUnknownElement and render its children. This lets you provide a fallback experience for all users.

Custom fallback pattern

Programmatically detect support for the <usermedia> element in JavaScript:

if ('HTMLUserMediaElement' in window) {
  // Use modern <usermedia> element logic
} else {
  // Fallback to legacy getUserMedia() API
}

Use this detection logic to add a standard button inside the <usermedia> element to trigger the legacy getUserMedia() API:

<usermedia id="stream-handler">
    <button id="fallback-stream-handler">
        Enable Camera and Mic
    </button>
</usermedia>
// Function for handling video/audio streams:
function handleStream (event) {
  /* ... */
}

if ('HTMLUserMediaElement' in window) {
  // In this case, we have <usermedia> element support:
  const streamHandler = document.getElementById('stream-handler');

  streamHandler.addEventListener('stream', event => {
    handleStream(event);
  });
} else {
  // <usermedia> element support is missing, so fall back instead:
  const fallbackStreamHandler = document.getElementById('fallback-stream-handler');

  fallbackStreamHandler.addEventListener('click', event => {
    navigator.mediaDevices.getUserMedia({video: true, audio: true}).then(handleStream);
  });
}

Migration for Origin Trial participants

For developers who integrated the experimental and generic <permission> element during the Origin Trial, transitioning to <usermedia> is designed to be minimal.

  1. Tag update: Replace <permission type="camera microphone"> with <usermedia> to ensure that all selectors targeting the previous <permission> elements are updated to use the <usermedia> element instead.
  2. Feature detection: Update checks from HTMLPermissionElement to HTMLUserMediaElement

The roadmap ahead

While the <usermedia> element handles combined audio and video requests, the roadmap for future Capability Elements includes:

  • <camera>: Focuses specifically on video-only scenarios.
  • <microphone>: Focuses specifically on audio-only scenarios.

You can see how these capability-specific elements help developers build more intuitive and trustworthy media experiences. For more information, see the Capability Elements technical guide.

联系我们 contact @ memedata.com