# SerialPort

> SerialPort opens an approved serial device, exposes byte streams and control signals, and defines close, disconnect, and error recovery behavior.

The `SerialPort` interface represents a serial port that a site has permission to access. Obtain one from `navigator.serial.requestPort()` or `navigator.serial.getPorts()`, open it with communication settings, then exchange bytes through its readable and writable streams ([WebSerial Standard](https://serial.spec.whatwg.org/#serialport), WHATWG).

The interface is limited to secure contexts and is also exposed in dedicated workers. The [Web Serial compatibility data](/compatibility/web-serial/) records support from Chrome and Edge 89 on desktop and Firefox 151. It records partial Android support from Chrome 138, full Chrome Android support from 148, partial Samsung Internet support from 30.0 and full support from 31.0, with no support recorded for Safari, Firefox for Android, or Android WebView (BCD `api.Serial`).

## Syntax

```js
await port.open(options);
port.readable;
port.writable;
port.connected;

port.getInfo();
await port.getSignals();
await port.setSignals(signals);
await port.close();
await port.forget();
```

`SerialPort` inherits from `EventTarget` and fires `connect` and `disconnect` events. It has no public constructor; the `Serial` interface creates instances after a previous grant or a user selection. Most methods complete asynchronously on the serial port task source defined by the standard.

## Members

| Member | Type | Meaning |
|---|---|---|
| `connected` | Boolean | Reports whether the port is logically connected to its device. |
| `readable` | `ReadableStream<Uint8Array>` or `null` | Receives bytes while the port is open. |
| `writable` | `WritableStream<BufferSource>` or `null` | Sends bytes while the port is open. |
| `getInfo()` | `SerialPortInfo` | Returns available USB vendor/product identifiers or a Bluetooth service class identifier. |
| `open(options)` | `Promise<undefined>` | Opens the port with serial communication options. |
| `getSignals()` | `Promise<SerialInputSignals>` | Reads input control signals. |
| `setSignals(signals)` | `Promise<undefined>` | Sets output control signals. |
| `close()` | `Promise<undefined>` | Closes the serial port; release the reader and writer stream locks before calling it. |
| `forget()` | `Promise<undefined>` | Revokes the site's permission for the port. |

`open()` requires `baudRate`. The standard also defines `dataBits` (7 or 8), `stopBits` (1 or 2), `parity` (`"none"`, `"even"`, or `"odd"`), `bufferSize`, and `flowControl` (`"none"` or `"hardware"`). MDN documents `open()` as returning a promise and rejecting if the port is already open or the opening attempt fails ([SerialPort.open()](https://developer.mozilla.org/en-US/docs/Web/API/SerialPort/open), MDN).

The streams carry bytes. Use `TextDecoderStream` and `TextEncoderStream` only when the device protocol is text. For a binary protocol, keep `Uint8Array` chunks and implement framing according to the device protocol. Chrome's serial guide shows direct byte reads, text transforms, writes through a stream writer, and the lock-release sequence needed before close ([Read from and write to a serial port](https://developer.chrome.com/docs/capabilities/serial), Chrome for Developers).

## Exceptions

The WebSerial Standard validates settings before asking the operating system to open the port. `open()` rejects with `InvalidStateError` when the port is not closed, `TypeError` for invalid options such as a zero baud rate, and `NetworkError` when the operating system fails to open the port. MDN lists the already-open and open-failure cases for `InvalidStateError` and `NetworkError`.

Read streams can error after the port opens. The standard names `BufferOverrunError`, `BreakError`, `FramingError`, and `ParityError` for nonfatal receive conditions. A device loss produces a network failure and changes the available stream state. Release reader and writer locks in `finally` blocks so error handling does not prevent later cleanup.

:::caution
Chrome's serial guide says a port can be closed when its readable and writable streams are unlocked. Cancel a pending reader so `read()` finishes, then release the reader and writer locks before calling `close()`. The standard's `close()` algorithm invokes `cancel()` on the readable stream and `abort()` on the writable stream; if the combined stream work rejects, `close()` rejects with the same reason ([WebSerial Standard](https://serial.spec.whatwg.org/#dom-serialport-close), WHATWG; [Read from and write to a serial port](https://developer.chrome.com/docs/capabilities/serial), Chrome for Developers).
:::

## Examples

The examples keep port selection separate from port operation. A missing `navigator.serial` branch gives the UI a working route to instructions for a native companion or a supported desktop browser.

### Opening an approved port and reporting failures

Reuse a previously granted port when one is available. Ask the user to choose only from a click handler, then classify cancellation and open failures without hiding other programming errors.

```js
async function connectSerial(status) {
  if (!("serial" in navigator)) {
    const instructions = Object.assign(document.createElement("a"), {
      href: "https://developer.chrome.com/docs/capabilities/serial",
      textContent: "Open Web Serial setup instructions",
      target: "_blank",
      rel: "noreferrer",
    });
    status.replaceChildren(instructions);
    return null;
  }
  const granted = await navigator.serial.getPorts();
  let port = granted[0] ?? null;
  if (!port) {
    try {
      port = await navigator.serial.requestPort();
    } catch (error) {
      if (error.name !== "NotFoundError") throw error;
      status.textContent = "No serial port was selected";
      return null;
    }
  }
  try {
    await port.open({ baudRate: 115200, dataBits: 8, stopBits: 1 });
    status.textContent = "Serial port opened";
    return port;
  } catch (error) {
    if (error.name !== "NetworkError" && error.name !== "InvalidStateError") throw error;
    status.textContent = `${error.name}: the serial port did not open`;
    return null;
  }
}

document.querySelector("#connect").addEventListener("click", () =>
  connectSerial(document.querySelector("#status")),
);
```

The standard requires transient activation for `requestPort()` and rejects a picker closed without a choice with `NotFoundError`. The returned `null` keeps later read and write code from running against an unopened port.

### Reading bytes and closing after an error

This complete page selects and opens a port, acquires a reader, displays received bytes, and releases the lock in every exit path. The reading coroutine owns `close()`: both a fatal read error and the stop helper reach the same `finally` cleanup. The stop helper clears the loop flag, cancels a pending read, waits for that cleanup, and reports whether closing succeeded. Run it from `https://` or `localhost` in a browser with Web Serial support.

```html
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>SerialPort read and close example</title>
<button id="connect" type="button">Connect</button>
<button id="disconnect" type="button" disabled>Disconnect</button>
<output id="status" aria-live="polite">Not connected</output>
<pre id="packets"></pre>
<script>
function startReading(port, onChunk, onError) {
  let keepReading = true;
  let reader;
  let closeError;
  const finished = (async () => {
    try {
      while (keepReading && port.readable) {
        reader = port.readable.getReader();
        try {
          for (;;) {
            const { value, done } = await reader.read();
            if (done) break;
            if (value) onChunk(value);
          }
        } catch (error) {
          onError(error);
          if (error.name === "NetworkError") {
            keepReading = false;
          }
        } finally {
          reader.releaseLock();
          reader = undefined;
        }
      }
    } finally {
      try {
        await port.close();
      } catch (error) {
        closeError = error;
        onError(error);
      }
    }
  })();

  return async function stop() {
    keepReading = false;
    try {
      await reader?.cancel();
    } finally {
      await finished;
    }
    return { closed: closeError === undefined, error: closeError };
  };
}

const connect = document.querySelector("#connect");
const disconnect = document.querySelector("#disconnect");
const status = document.querySelector("#status");
const packets = document.querySelector("#packets");
let stopReading;

function consumePacket(bytes) {
  packets.textContent += `${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(" ")}\n`;
}

function showSerialError(error) {
  status.textContent = `${error.name}: ${error.message}`;
}

connect.addEventListener("click", async () => {
  if (!("serial" in navigator)) {
    status.textContent = "Web Serial is not supported in this browser";
    return;
  }
  try {
    const port = await navigator.serial.requestPort();
    await port.open({ baudRate: 115200 });
    stopReading = startReading(port, consumePacket, showSerialError);
    connect.disabled = true;
    disconnect.disabled = false;
    status.textContent = "Reading from the serial port";
  } catch (error) {
    if (error.name !== "NotFoundError") showSerialError(error);
  }
});

disconnect.addEventListener("click", async () => {
  const result = await stopReading?.();
  stopReading = undefined;
  connect.disabled = false;
  disconnect.disabled = true;
  if (result?.closed) status.textContent = "Serial port closed";
});
</script>
</html>
```

The error callback distinguishes a line fault from device loss by `error.name` and also makes a failed `close()` visible. The stop helper reports whether that close succeeded, so the **Disconnect** handler does not replace a close error with a success message. Setting `keepReading` before canceling prevents the outer loop from acquiring a new reader after the canceled read finishes. The inner `finally` releases each reader; the outer `finally` then calls `close()` exactly once, including when a fatal read error ends the coroutine without a click on **Disconnect**.

## See also

- [Web Serial API](/reference/capabilities/web-serial/)
- [WebUSB API](/reference/capabilities/web-usb/)
- [WebSerial Standard: SerialPort interface](https://serial.spec.whatwg.org/#serialport) (whatwg.org)
- [SerialPort](https://developer.mozilla.org/en-US/docs/Web/API/SerialPort) (MDN)
- [Read from and write to a serial port](https://developer.chrome.com/docs/capabilities/serial) (Chrome for Developers)