SerialPort:getInfo() 方法

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

注意:此功能在 专用 Web Workers 中可用。

SerialPort 接口的 getInfo() 方法返回一个包含设备标识信息的对象,这些信息可通过该端口获得。

语法

js
getInfo()

参数

无。

返回值

包含以下属性的对象:

usbVendorId

如果该端口是 USB 设备的一部分,此属性是一个无符号短整数,用于标识设备的供应商。如果不是,则为 undefined

usbProductId

如果该端口是 USB 设备的一部分,此属性是一个无符号短整数,用于标识 USB 设备。如果不是,则为 undefined

bluetoothServiceClassId 实验性

如果该端口是蓝牙 RFCOMM 服务,此属性是一个无符号长整数或字符串,表示设备的蓝牙服务类 ID。如果不是,则为 undefined

示例

此代码段在按下 <button> 时调用 Serial.requestPort() 方法。我们将过滤器传递给 requestPort() 以过滤 Arduino Uno USB 设备。请求端口后,我们调用 getInfo() 来返回设备的 usbProductIdusbVendorId

html
<button id="connect">Connect</button>
js
const connectBtn = document.getElementById("connect");

// Filter for devices with the Arduino Uno USB Vendor/Product IDs
const filters = [
  { usbVendorId: 0x2341, usbProductId: 0x0043 },
  { usbVendorId: 0x2341, usbProductId: 0x0001 }
];

connectBtn.addEventListener("click", () => {
  try {
    // Prompt the user to select an Arduino Uno device
    const port = await navigator.serial.requestPort({ filters });

    // Return the device's identifying info
    const { usbProductId, usbVendorId } = port.getInfo();
  } catch (e) {
    // The user didn't select a device
  }
});

规范

规范
Web Serial API
# dom-serialport-getinfo

浏览器兼容性