Skip to content

Instantly share code, notes, and snippets.

@reillyeon
Created August 20, 2022 04:11
Show Gist options
  • Save reillyeon/18bdd96e770c30f4ae0874299c831e9b to your computer and use it in GitHub Desktop.
Save reillyeon/18bdd96e770c30f4ae0874299c831e9b to your computer and use it in GitHub Desktop.
Redirecting the Chrome terminal to a serial terminal

Instructions

The following instructions will redirect an SSH connection or local console to a connected serial device.

Step 1

Open the Terminal app or Secure Shell extension and connect to your target system.

Step 2

Open chrome://inspect/#pages, find the tab in which the terminal is running and click "Inspect".

Step 3

Paste the following code into the JavaScript console:

async function attachToSerial(options) {
  const port = await navigator.serial.requestPort();
  await port.open(options);
  
  const reader = port.readable.getReader();
  (async () => {
    while (true) {
      const { value, done } = await reader.read();
      if (done) {
        return;
      }
      window.term_.io.sendString((new TextDecoder()).decode(value));
    }
  })();

  const savedPrintFunction = window.term_.io.print;
  window.term_.io.print = (s) => {
    const writer = port.writable.getWriter();
    writer.write((new TextEncoder()).encode(s));
    writer.releaseLock();
  };
  
  window.detachFromSerial = async () => {
    reader.releaseLock();
    await port.close();
    window.term_.io.print = savedPrintFunction;
    delete window.detachFromSerial;
  };
}

Step 4

Run attachToSerial({ baudRate: 9600 }) and select the serial device in the chooser presented. Modify the baudRate parameter to match the configuration of the device.

The serial terminal should now have full control over the connection.

Step 5

On the serial terminal type the following commands to test its functionality and configure it for use with a dumb terminal:

export TERM=vt100
stty rows 24 cols 80

Since the process above has effectively unplugged the connection from one terminal and substituted another. Adjust the stty command if the terminal is not the standard 80×24 geometry.

It can be helpful to run screen on the connected system to provide better compatibility between modern applications and older terminals.

Step 6

To move the connection back to the local terminal emulator run detachFromSerial() on the DevTools console.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment