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

SerialPort: connected property

· 52CE 我爱测

The **`connected`** read-only property of the SerialPort interface returns a boolean value that indicates whether the port is logically connected to the device.

Web Serial APIwindow_and_dedicated

The connected read-only property of the SerialPort interface returns a boolean value that indicates whether the port is logically connected to the device.

Value

A boolean — true if the port is logically connected, and false if not.

Description

When a wireless device goes out of range of the host, any wireless serial port opened by a web app automatically closes, even though it stays logically connected. In such cases, the web app could attempt to reopen the port using SerialPort.open().

However, if the wireless device was intentionally disconnected (for example, if the user chose to disconnect it using the operating system control panel), the web app should refrain from reopening the port to prevent reconnecting to the wireless device.

The following snippet shows how the connected property can be used to distinguish between these two cases:

const ports = await navigator.serial.getPorts();
for (const port of ports) {
  if (port.connected) {
    // The port is logically connected
    // automatically try to reopen the port
    await port.open({ baudRate: 9600 });
  } else {
    // The port is not logically connected; at this point you could
    // prompt the user to make sure the Bluetooth device is available, and
    // Show a "connect" button to allow them to try opening the port if desired
  }
}

Examples

Logging when a port is connected

The following snippet invokes Serial.requestPort() when the user presses a button, prompting them to choose a serial port to connect to, then logs a message to the console reporting the connection status:

requestPortButton.addEventListener("click", async () => {
  const port = await navigator.serial.requestPort();
  console.log(`Requested serial port. Connected: ${port.connected}`);
});

Logging connection status on connect and disconnect

You can use the following snippet to log the connection status when the SerialPort.connect_event and SerialPort.disconnect_event events fire:

navigator.serial.addEventListener("connect", ({ target: port }) => {
  console.log(`Connect event fired. Connected: ${port.connected}`);
});

navigator.serial.addEventListener("disconnect", ({ target: port }) => {
  console.log(`Disconnect event fired. Connected: ${port.connected}`);
});

Specifications

Browser compatibility

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

资料来源与适用范围

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

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

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