大网数据广告活动
Web 标准与前端开发

MediaDeviceInfo: groupId property

· 52CE 我爱测

The **`groupId`** read-only property of the MediaDeviceInfo interface returns a string that is a group identifier.

Media Capture and Streams

The groupId read-only property of the MediaDeviceInfo interface returns a string that is a group identifier.

Two devices have the same group identifier if they belong to the same physical device; for example, a monitor with both a built-in camera and microphone.

Value

A string which uniquely identifies the group of related devices to which this device belongs.

Examples

In this example, we assemble a list of the devices which are part of the same group as a given device. This might be used to produce a user interface that gathers associated devices together for presentation purposes, or to make it easy for the user to choose to use the built-in camera and microphone on the same display at the same time.

const getDeviceGroup = (mainDevInfo) => {
  let devList = [];

  navigator.mediaDevices.enumerateDevices().then((devices) => {
    devices.forEach((device) => {
      if (device.groupId === mainDevInfo.groupId) {
        devList.push(device);
      }
    });
  });

  return devList;
};

The getDeviceGroup() function takes as input the MediaDeviceInfo object describing the device for which a group list is to be built. The function starts by initializing the result array, devList, to be an empty array.

Then MediaDevices.enumerateDevices is called to get the list of all media devices. Once the promise resolves, we walk the list using Array.forEach. For each device, if its groupId matches the main device's groupId, we push the MediaDeviceInfo object onto the list.

Finally, the list, which now contains a MediaDeviceInfo object for each device in the same group, is returned to the caller.

This could be altered easily to either leave out the passed-in device from the returned list, or to place it at the top of the list, by comparing the two objects' MediaDeviceInfo.deviceId values, only pushing the device onto the result list if it doesn't match.

This version of the example puts the passed-in device at the top of the result list, then adds any other members of the group that are found:

const getDeviceGroup = (mainDevInfo) => {
  let devList = [mainDevInfo];

  navigator.mediaDevices.enumerateDevices().then((devices) => {
    devices.forEach((device) => {
      if (
        device.groupId === mainDevInfo.groupId &&
        device.deviceId !== mainDevInfo.deviceId
      ) {
        devList.push(device);
      }
    });
  });

  return devList;
};

Specifications

Browser compatibility

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。