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
}
}SerialPort: connected property / notebook
SerialPort: connected property
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
requestPortButton.addEventListener("click", async () => {
const port = await navigator.serial.requestPort();
console.log(`Requested serial port. Connected: ${port.connected}`);
});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}`);
});