SerialPort: connected property
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Secure context: This feature is available only insecure contexts (HTTPS), in some or allsupporting browsers.
Experimental:This is anexperimental technology
Check theBrowser compatibility table carefully before using this in production.
Note: This feature is available inDedicated Web Workers.
Theconnected read-only property of theSerialPort interface returns a boolean value that indicates whether the port islogically connected to the device.
In this article
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 usingSerialPort.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 theconnected 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 }}Value
A boolean —true if the port is logically connected, andfalse if not.
Examples
>Logging when a port is connected
The following snippet invokesSerial.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 theconnect anddisconnect 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
| Specification |
|---|
| Web Serial API> # dom-serialport-connected> |