Bluetooth RFCOMM updates in Web Serial

François Beaufort
François Beaufort

The Web Serial API supports communicating with RFCOMM services on paired Bluetooth Classic devices from Chrome 117 on desktop. For example, this allows wireless earbuds to use RFCOMM to manage audio settings and firmware updates. Check out Serial over Bluetooth on the web to learn more.

From Chrome 130 for desktop, an improvement to the Web Serial API lets web apps detect when a Bluetooth RFCOMM serial port is available, without having to open the port. This prevents unnecessary reconnections when the wireless device was intentionally disconnected.

When a wireless device goes out of range of the host, any wireless serial port opened by a web app automatically closes. In such cases, the web app may attempt to reopen the port with the SerialPort open() method. However, if the wireless device was intentionally disconnected (for example, by the user from the operating system control panel), the web app should refrain from reopening the port to prevent reconnecting to the wireless device.

By exposing the logical connection state of the wireless device hosting the wireless serial port through a new boolean SerialPort connected attribute, web apps can now distinguish these cases, and only reconnect if the disconnection was unintentional.

The SerialPort connected attribute is true for wireless serial ports if the wireless device hosting the port has any active connections to the system. For wired serial ports, it is true if the port is physically attached to the system.

The following snippet shows you how to check which devices are available and potentially connect to them automatically.

const ports = await navigator.serial.getPorts();
for (const port of ports) {
  if (port.connected) {
    // Automatically try to connect to the Bluetooth device.
    await port.open({ baudRate: 9600 });
  } else {
    // Otherwise, when the port is not logically connected:
    // 1. Prompt the user to make sure the Bluetooth device is available.
    // 2. Show a "connect" button to try opening the port.
  }
}

Previously, only wired serial ports dispatched connect and disconnect events. Bluetooth RFCOMM serial ports now dispatch these events when the port becomes logically connected or disconnected.

Demo

SerialPort connected demo.

Resources

Acknowledgments

Thanks to Jack Hsieh and Reilly Grant for their reviews.