The Web Serial API provides a way for websites to read from and write to serial devices. These devices may be connected via a serial port, or be USB or Bluetooth devices that emulate a serial port.
The Web Serial API is one of a set of APIs that allow websites to communicate with peripherals connected to a user's computer. It provides the ability to connect to devices that are required by the operating system to communicate via the serial API, rather than USB which can be accessed via the WebUSB API
, or input devices that can be accessed via WebHID API
.
Examples of serial devices include 3D printers, and microcontrollers such as the BBC micro:bit board.
The following examples demonstrate some of the functionality provided by the Web Serial API.
The following example shows how to check for available ports and allows the user to grant it permission to access additional ports.
The connect
and disconnect
events let sites react when a device is connected or disconnected from the system. The getPorts()
method is then called to see connected ports 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 click
event handler on a button for this task. A filter is passed to 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) => {
});
navigator.serial.addEventListener("disconnect", (e) => {
});
navigator.serial.getPorts().then((ports) => {
});
button.addEventListener("click", () => {
const usbVendorId = 0xabcd;
navigator.serial
.requestPort({ filters: [{ usbVendorId }] })
.then((port) => {
})
.catch((e) => {
});
});
The following example shows how to read data from a port. The outer loop handles non-fatal errors, creating a new reader until a fatal error is encountered and SerialPort.readable
becomes null
.
while (port.readable) {
const reader = port.readable.getReader();
try {
while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}
}
} catch (error) {
} finally {
reader.releaseLock();
}
}