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

Serial

· 52CE 我爱测

The `Serial` interface of the Web Serial API provides attributes and methods for finding and connecting to serial ports from a web page.

Web Serial APIwindow_and_dedicated

The Serial interface of the Web Serial API provides attributes and methods for finding and connecting to serial ports from a web page.

Instance methods

  • Serial.requestPort()

    • : Returns a Promise that resolves with an instance of SerialPort representing the device chosen by the user. This method must be called via transient activation.
  • Serial.getPorts()

    • : Returns a Promise that resolves with an array of SerialPort objects representing serial ports connected to the host that the origin has permission to access.

Events

The following events are available to Serial via event bubbling from SerialPort:

  • SerialPort SerialPort.connect_event event
    • : An event fired when a port has been connected to the device.
  • SerialPort SerialPort.disconnect_event event
    • : An event fired when a port has been disconnected from the device.

Examples

Basic usage

The following example shows how a site can check for available ports and allow the user to grant it permission to access additional ports.

On load event listeners are added for the SerialPort.connect_event and SerialPort.disconnect_event events so that the site can react when a device is connected or disconnected from the system. The Serial.getPorts() method is then called to see which ports are connected that the site already has access to.

If the site doesn't have access to any connected ports it has to wait until it has user activation to proceed. In this example we use a Element.click_event event handler on a button for this task. A filter is passed to Serial.requestPort() with a USB vendor ID in order to limit the set of devices shown to the user to only USB devices built by a particular manufacturer.

navigator.serial.addEventListener("connect", (e) => {
  // Connect to `e.target` or add it to a list of available ports.
});

navigator.serial.addEventListener("disconnect", (e) => {
  // Remove `e.target` from the list of available ports.
});

navigator.serial.getPorts().then((ports) => {
  // Initialize the list of available ports with `ports` on page load.
});

button.addEventListener("click", () => {
  const usbVendorId = 0xabcd;
  navigator.serial
    .requestPort({ filters: [{ usbVendorId }] })
    .then((port) => {
      // Connect to `port` or add it to the list of available ports.
    })
    .catch((e) => {
      // The user didn't select a port.
    });
});

Specifications

Browser compatibility

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

资料来源与适用范围

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

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

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