Serial
Secure context
This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
Description
The Serial
interface of the Web Serial API
provides attributes and methods for finding and connecting to serial ports from a web page.
Event Handlers
Serial.onconnect
- An event handler called when a port has been connected to the device.
Serial.ondisconnect
- An event handler called when a port has been disconnected from the device.
Methods
Serial.requestPort()
-
Returns a
Promise
that resolves with an instance ofSerialPort
representing the device chosen by the user or rejects if no device was selected.This method must be called with user activation.
Serial.getPorts()
-
Returns a
Promise
that resolves with an array ofSerialPort
objects representing serial ports connected to the host which the origin has permission to access.
Examples
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 connect
and disconnect
events so that the site can react when a device is connected or disconnected from the system. The 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 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) => {
// 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 = ...;
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
Specification | Status | Comment |
---|---|---|
Web Serial API The definition of 'Serial' in that specification. |
Draft | Initial definition. |
Browser compatibility
BCD tables only load in the browser