Interactive Terminal Emulator for the Web – xterm.js

Category: Javascript , Recommended | October 19, 2026
Authorxtermjs
Last UpdateOctober 19, 2026
LicenseMIT
Views0 views
Interactive Terminal Emulator for the Web – xterm.js

xterm.js is a JavaScript terminal emulator that displays interactive command-line sessions inside web applications.

It renders ANSI escape sequences, full-screen programs such as Vim and tmux, Unicode text, and mouse input.

For actual shell execution, xterm.js connects to a command environment, typically a backend pseudoterminal (PTY) over a WebSocket.

It handles terminal display and input, but the library itself does not include Bash, PowerShell, or a command interpreter.

Browser-only applications can implement their own command handlers.

Features

  • Terminal emulation for ANSI colors, cursor control, and full-screen programs.
  • Keyboard, mouse, selection, paste, and scrollback handling.
  • Unicode, CJK characters, emojis, and input method editors.
  • Configurable fonts, cursor styles, colors, and contrast.
  • Optional WebGL renderer for GPU-accelerated text rendering.
  • Addons for automatic sizing, search, links, images, and serialization.
  • Screen reader mode and custom key handlers.
  • An extensible public API for buffers, links, decorations, and terminal sequences.

Use Cases

  • Browser IDEs: Display a real development shell beside an editor, including interactive programs and terminal control sequences.
  • Server administration: Build authenticated SSH or container console screens around a remote PTY service.
  • Developer dashboards: Present live process output, logs, or build commands in an ANSI-aware terminal view.
  • Coding lessons: Connect an isolated execution environment to a terminal students can control from a browser.

How to Use It

Installation

Install xterm.js with NPM.

npm install @xterm/xterm

Basic Usage

Create a visible container with a defined height before opening the terminal. This example below displays a terminal prompt.

<div id="terminal" style="width:100%;height:320px"></div>
import { Terminal } from '@xterm/xterm';
import '@xterm/xterm/css/xterm.css';
const terminal = new Terminal({
  cursorBlink: true,
  fontFamily: 'monospace',
  theme: { background: '#101827', foreground: '#f3f4f6' }
});
terminal.open(document.getElementById('terminal'));
terminal.writeln('Terminal ready');
terminal.write('$ ');

CDN Setup for a Plain HTML Page

The browser build and stylesheet can also load directly from a CDN. This example runs in a regular HTML file after its remote assets load.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@xterm/[email protected]/css/xterm.css">
</head>
<body>
  <div id="terminal" style="width:100%;height:320px"></div>
  <script src="https://cdn.jsdelivr.net/npm/@xterm/[email protected]/lib/xterm.js"></script>
  <script>
    const terminal = new Terminal({ cursorBlink: true });
    terminal.open(document.getElementById('terminal'));
    terminal.writeln('Hello from xterm.js');
    terminal.write('$ ');
  </script>
</body>
</html>

Connect a Remote Terminal

A remote shell requires a backend that authenticates each session, creates a PTY, enforces process permissions, and manages session cleanup. node-pty can manage a PTY in Node.js.

The example below assumes your backend sends terminal output as UTF-8 WebSocket text frames and accepts terminal input as text frames or raw binary frames. The example URL is a placeholder for your authenticated WebSocket endpoint.

onBinary handles non-UTF-8 input such as legacy mouse reports. The callback receives a JavaScript string containing byte values. Convert it to bytes before transport.

The backend must accept both frame types and write the decoded data to the PTY. Implement PTY resize messages and output flow control through your application’s own protocol.

const socket = new WebSocket('wss://example.com/terminal');
socket.addEventListener('message', event => {
  if (typeof event.data === 'string') {
    terminal.write(event.data);
  }
});
const inputListener = terminal.onData(data => {
  if (socket.readyState === WebSocket.OPEN) {
    socket.send(data);
  }
});
const binaryListener = terminal.onBinary(data => {
  if (socket.readyState === WebSocket.OPEN) {
    const bytes = Uint8Array.from(data, char => char.charCodeAt(0));
    socket.send(bytes);
  }
});
socket.addEventListener('close', () => {
  inputListener.dispose();
  binaryListener.dispose();
});

Fit the Terminal to Its Container

Install the Fit addon and load it after the terminal has opened inside a visible element. Recalculate the terminal dimensions when the container changes size. A connected PTY must receive its own resize notification through your backend protocol. Debounce frequent resize updates before forwarding them to the PTY.

npm install @xterm/addon-fit
import { FitAddon } from '@xterm/addon-fit';
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
fitAddon.fit();
const container = document.getElementById('terminal');
const observer = new ResizeObserver(() => fitAddon.fit());
observer.observe(container);
terminal.onResize(({ cols, rows }) => {
  console.log('Terminal dimensions:', cols, rows);
});
// Call observer.disconnect() during component cleanup.

Configure Colors, Fonts, and Cursor Behavior

Most terminal settings can change after initialization through terminal.options. Assign a new object when changing a nested object such as theme.

terminal.options.fontSize = 15;
terminal.options.cursorStyle = 'bar';
terminal.options.theme = {
  ...terminal.options.theme,
  background: '#0b1020',
  foreground: '#e2e8f0',
  cursor: '#38bdf8',
  selectionBackground: '#334155'
};

Enable Web Links and WebGL Rendering

Web links and GPU rendering use optional addons. The WebGL addon requires a browser with a compatible WebGL2 environment. The terminal can use its built-in DOM renderer if the WebGL addon fails to initialize.

npm install @xterm/addon-web-links @xterm/addon-webgl
import { WebLinksAddon } from '@xterm/addon-web-links';
import { WebglAddon } from '@xterm/addon-webgl';
terminal.loadAddon(new WebLinksAddon());
try {
  terminal.loadAddon(new WebglAddon());
} catch (error) {
  console.warn('WebGL renderer unavailable', error);
}

Inspect the Terminal Buffer

Read the active buffer when an application needs to inspect terminal text. Buffer lines can change after subsequent writes, so read a line and process its contents immediately.

const buffer = terminal.buffer.active;
const currentLine = buffer.getLine(buffer.baseY + buffer.cursorY);
const text = currentLine?.translateToString(true) ?? '';
console.log(text);

Configuration Options

Appearance and typography

  • cursorBlink (boolean): Blink the cursor.
  • cursorStyle ('block' | 'underline' | 'bar'): Focused cursor: 'block', 'underline', or 'bar'.
  • cursorInactiveStyle ('outline' | 'block' | 'bar' | 'underline' | 'none'): Unfocused cursor: 'outline', 'block', 'bar', 'underline', or 'none'.
  • cursorWidth (number): Bar cursor width in CSS pixels.
  • customGlyphs (boolean): Render custom box and block drawing glyphs when the renderer permits it. Default: true.
  • drawBoldTextInBrightColors (boolean): Render bold text using bright ANSI palette colors. Default: true.
  • fontFamily (string): Font stack used for terminal characters.
  • fontSize (number): Font size for terminal text.
  • fontWeight (FontWeight): Weight for normal text. Accepts 'normal', 'bold', numeric weights, and string weights from '100' through '900'.
  • fontWeightBold (FontWeight): Weight for bold text. Uses the same accepted values as fontWeight.
  • letterSpacing (number): Whole-pixel spacing between characters.
  • lineHeight (number): Line-height multiplier.
  • minimumContrastRatio (number): Adjust terminal foreground colors to meet the requested contrast ratio. Default: 1 (no adjustment).
  • rescaleOverlappingGlyphs (boolean): Rescale selected wide-looking single-cell glyphs. Default: false.
  • theme (ITheme): ITheme colors for text, cursor, selection, and ANSI palette.
  • allowTransparency (boolean): Permit transparent backgrounds. Set before open(). Can affect performance.

Input and selection

  • altClickMovesCursor (boolean): Move the prompt cursor on Alt-click. Default: true.
  • convertEol (boolean): Interpret line feeds as moving to the beginning of the next line. Usually unnecessary with a PTY.
  • disableStdin (boolean): Disable terminal input.
  • ignoreBracketedPasteMode (boolean): Ignore bracketed-paste mode even when an application requests it.
  • linkHandler (ILinkHandler | null): ILinkHandler for OSC 8 hyperlinks, including activation security.
  • macOptionClickForcesSelection (boolean): Allow Option-click selection even when mouse reporting is enabled.
  • macOptionIsMeta (boolean): Handle macOS Option as the Meta key.
  • rightClickSelectsWord (boolean): Select a word with the right mouse button.
  • screenReaderMode (boolean): Expose additional DOM content for supported screen readers.
  • tabStopWidth (number): Number of character cells between tab stops.
  • wordSeparator (string): Characters considered separators during word selection.

Scrolling and output

  • fastScrollSensitivity (number): Fast-scroll multiplier with Alt pressed.
  • reflowCursorLine (boolean): Reflow the cursor line when resizing. Default: false.
  • scrollback (number): Number of retained lines outside the viewport. Default: 1000.
  • scrollOnEraseInDisplay (boolean): Push erased ED2 viewport content into scrollback.
  • scrollOnUserInput (boolean): Scroll to the bottom on user input. Default: true.
  • scrollSensitivity (number): Normal scroll speed multiplier.
  • smoothScrollDuration (number): Scroll animation duration in milliseconds. Set 0 for instant scrolling.

Integration and advanced behavior

  • allowProposedApi (boolean): Enable experimental APIs. Default: false.
  • documentOverride (any | null): Use a specific Document for multi-window integrations.
  • logLevel (LogLevel): Logging threshold: 'trace', 'debug', 'info', 'warn', 'error', or 'off'. Default: 'info'.
  • logger (ILogger | null): ILogger implementation used in place of console.
  • overviewRuler (IOverviewRulerOptions): IOverviewRulerOptions for the overview ruler.
  • windowOptions (IWindowOptions): IWindowOptions for terminal-initiated window operations and reports. Disabled by default.
  • windowsPty (IWindowsPty): IWindowsPty settings for Windows PTY behavior.

Initialization-only dimensions

Public itemDescription
colsInitial terminal column count.
rowsInitial terminal row count.

Theme Colors

Set the following ITheme properties inside theme.

Base, selection, and scroll bar colors

Public itemDescription
foregroundDefault foreground color.
backgroundDefault background color.
cursorCursor color.
cursorAccentForeground color inside a block cursor.
selectionBackgroundBackground color of selected text.
selectionForegroundOptional text color for selections.
selectionInactiveBackgroundSelection color while the terminal lacks focus.
scrollbarSliderBackgroundScroll bar thumb at rest.
scrollbarSliderHoverBackgroundScroll bar thumb on hover.
scrollbarSliderActiveBackgroundScroll bar thumb when active.
overviewRulerBorderBorder color beside the overview ruler.

ANSI palette

Public itemDescription
blackANSI black.
redANSI red.
greenANSI green.
yellowANSI yellow.
blueANSI blue.
magentaANSI magenta.
cyanANSI cyan.
whiteANSI white.
brightBlackBright ANSI black.
brightRedBright ANSI red.
brightGreenBright ANSI green.
brightYellowBright ANSI yellow.
brightBlueBright ANSI blue.
brightMagentaBright ANSI magenta.
brightCyanBright ANSI cyan.
brightWhiteBright ANSI white.
extendedAnsiArray of extended ANSI palette colors, indices 16 through 255.

Nested Option Objects

overviewRuler, windowsPty, logger, linkHandler, and windowOptions accept public option objects. Window operations start disabled for security reasons. Only activate the exact operations your backend expects.

IOverviewRulerOptions

Public itemDescription
widthOverview ruler width in pixels.
showTopBorderDisplay the top border.
showBottomBorderDisplay the bottom border.

IWindowsPty

Public itemDescription
backendBackend type: 'conpty' or 'winpty'.
buildNumberWindows build number for compatibility behavior.

ILogger callbacks

Public itemDescription
trace(message, ...args)Trace log handler.
debug(message, ...args)Debug log handler.
info(message, ...args)Informational log handler.
warn(message, ...args)Warning log handler.
error(message, ...args)Error log handler.

ILinkHandler members

Public itemDescription
activate(event, text, range)Handle activation of an OSC 8 hyperlink.
hover(event, text, range)Optional hover handler.
leave(event, text, range)Optional pointer-leave handler.
allowNonHttpProtocolsExplicitly opt in to hyperlinks with non-HTTP(S) protocols. Validate untrusted URLs first.

IWindowOptions permissions

Public itemDescription
restoreWinAllow restoring the window.
minimizeWinAllow minimizing the window.
setWinPositionAllow changing its pixel position.
setWinSizePixelsAllow changing its pixel dimensions.
raiseWinAllow raising the window.
lowerWinAllow lowering the window.
refreshWinAllow requests to refresh the window.
setWinSizeCharsAllow changing dimensions in terminal cells.
maximizeWinAllow maximizing the window.
fullscreenWinAllow fullscreen requests.
getWinStateAllow window state reports.
getWinPositionAllow window position reports.
getWinSizePixelsAllow window size reports in pixels.
getScreenSizePixelsAllow screen size reports in pixels.
getCellSizePixelsAllow character cell size reports in pixels.
getWinSizeCharsAllow window size reports in terminal cells.
getScreenSizeCharsAllow screen size reports in terminal cells.
getIconTitleAllow icon title reports.
getWinTitleAllow window title reports.
pushTitleAllow pushing a title onto the title stack.
popTitleAllow popping the previously saved title.
setWinLinesAllow setting terminal window height in lines.

Terminal Properties and Events

Terminal exposes state and lifecycle information through public properties. The terminal events use callback subscriptions and return a disposable listener handle.

const subscription = terminal.onData(data => console.log(data));
subscription.dispose();

Terminal properties

Public itemDescription
elementRendered terminal root element, or undefined before opening.
textareaInput textarea, or undefined before opening.
colsCurrent viewport column count (read-only).
rowsCurrent viewport row count (read-only).
optionsReadable and writable terminal option collection.
bufferIBufferNamespace for normal, alternate, and active buffers.
markersRegistered markers (experimental).
modesRead-only terminal modes updated by terminal sequences.
parserEscape-sequence parser registration API.
unicodeUnicode version API (experimental).
Terminal.stringsStatic ILocalizableStrings object.

Terminal events

Public itemDescription
onBell(listener)Terminal bell is triggered.
onBinary(listener)Non-UTF-8 terminal input, including legacy mouse reports. The callback receives a binary-encoded JavaScript string.
onCursorMove(listener)Cursor position changes.
onData(listener)Terminal input data is generated by typing or pasting.
onKey(listener)A key is pressed. Callback receives { key, domEvent }.
onLineFeed(listener)A line feed occurs.
onRender(listener)A row range is rendered. Callback receives { start, end }.
onWriteParsed(listener)Pending written data has been parsed, at most once per frame.
onResize(listener)The terminal dimensions change. Callback receives { cols, rows }.
onScroll(listener)The viewport scrolls. Callback receives its new position.
onSelectionChange(listener)The text selection changes.
onTitleChange(listener)An OSC 0 or OSC 2 title update occurs.

Terminal Methods

The methods below belong to the public Terminal class. Handler registrations that return IDisposable can be released with dispose(). APIs marked experimental require allowProposedApi: true and can change between versions.

const selectedText = terminal.getSelection();
terminal.clearSelection();
terminal.scrollToBottom();

Lifecycle and input

Public itemDescription
open(parent)Create the terminal inside a visible HTMLElement.
dispose()Destroy the terminal and release its resources.
focus()Focus the terminal.
blur()Remove terminal focus.
input(data, wasUserInput?)Send application input and fire onData. Optional flag controls user-input behavior.
write(data, callback?)Queue text or UTF-8 Uint8Array data for terminal output, optionally run a completion callback.
writeln(data, callback?)Write terminal output and append a line break.
paste(data)Submit text through the terminal paste handling.
resize(columns, rows)Change the terminal geometry.
reset()Perform a full terminal reset.
clear()Clear the buffer and preserve the prompt line.
refresh(start, end)Request a redraw for an inclusive viewport row range.
clearTextureAtlas()Clear the active WebGL renderer texture atlas.
loadAddon(addon)Activate an addon that implements ITerminalAddon.

Selection and scrolling

Public itemDescription
hasSelection()Return whether text is selected.
getSelection()Return selected text.
getSelectionPosition()Return the selected buffer range, or undefined.
clearSelection()Clear any active selection.
select(column, row, length)Select text from a starting column and row for a given length.
selectAll()Select all terminal buffer text.
selectLines(start, end)Select a range of lines.
scrollLines(amount)Scroll by a signed number of lines.
scrollPages(pageCount)Scroll by pages.
scrollToTop()Move the viewport to the beginning of scrollback.
scrollToBottom()Move the viewport to the bottom.
scrollToLine(line)Move the viewport to a specific buffer line.

Input handlers and extensions

Public itemDescription
attachCustomKeyEventHandler(handler)Process keyboard events before the terminal. Return false to reject an event.
attachCustomWheelEventHandler(handler)Process wheel events before the terminal. Return false to reject an event.
registerLinkProvider(provider)Register custom link detection. Returns a disposable registration.
registerCharacterJoiner(handler)Register a WebGL character joiner and return its numeric ID (experimental).
deregisterCharacterJoiner(joinerId)Remove an experimental character joiner.
registerMarker(cursorYOffset?)Attach a marker to a normal-buffer line. The public TypeScript return type is IMarker; the result can be undefined in conditions where a marker cannot be created.
registerDecoration(options)Create a buffer decoration and return IDecoration or undefined (experimental).

Buffers, Parser Hooks, and Extensions

These core APIs support tools that inspect terminal output, process escape sequences, or draw decorations. Parser hooks, buffer state, and terminal output should be handled as untrusted data when their source is a remote shell.

IBufferNamespace

Public itemDescription
activeCurrent normal or alternate buffer.
normalNormal buffer.
alternateAlternate-screen buffer.
onBufferChange(listener)Event fired when the active buffer changes.

IBuffer

Public itemDescription
typeBuffer kind: 'normal' or 'alternate'.
cursorXCursor column relative to the viewport.
cursorYCursor row relative to the viewport.
viewportYFirst buffer line in the current viewport.
baseYFirst line of the bottommost viewport.
lengthTotal buffer line count.
getLine(y)Read an IBufferLine or undefined at a zero-based buffer index.
getNullCell()Create a reusable blank IBufferCell.

IBufferLine

Public itemDescription
isWrappedWhether this line continues a wrapped line.
lengthNumber of cells.
getCell(x, cell?)Return a cell at the column, optionally populate an existing cell.
translateToString(trimRight?, startColumn?, endColumn?)Read cell text as a JavaScript string.

IBufferCell

Public itemDescription
getWidth()Character cell width.
getChars()Cell text.
getCode()Cell Unicode code point.
getFgColorMode()Foreground color mode.
getBgColorMode()Background color mode.
getFgColor()Foreground color value.
getBgColor()Background color value.
isBold()Whether bold styling is active.
isItalic()Whether italic styling is active.
isDim()Whether dim styling is active.
isUnderline()Whether underline styling is active.
isBlink()Whether blink styling is active.
isInverse()Whether inverse coloring is active.
isInvisible()Whether invisibility is active.
isStrikethrough()Whether strikethrough styling is active.
isOverline()Whether overline styling is active.
isFgRGB()Whether the foreground uses an RGB value.
isBgRGB()Whether the background uses an RGB value.
isFgPalette()Whether the foreground uses an ANSI palette entry.
isBgPalette()Whether the background uses an ANSI palette entry.
isFgDefault()Whether the foreground uses the default color.
isBgDefault()Whether the background uses the default color.
isAttributeDefault()Whether the cell has default attribute data.

IParser methods

Parser callbacks return true when they handle a sequence and false when normal parsing should continue. They can also return a Promise. Each registration returns an IDisposable.

Public itemDescription
registerCsiHandler(id, callback)Intercept a CSI sequence identified by prefix, intermediates, and final byte.
registerDcsHandler(id, callback)Intercept a DCS sequence and its parameters.
registerEscHandler(id, handler)Intercept an ESC sequence.
registerOscHandler(ident, callback)Intercept an OSC sequence by numeric identifier.

IFunctionIdentifier

Public itemDescription
prefixOptional sequence prefix.
intermediatesOptional intermediate bytes.
finalRequired final character.

Unicode extension API (experimental)

Public itemDescription
unicode.register(provider)Register an IUnicodeVersionProvider.
unicode.versionsAvailable Unicode provider versions.
unicode.activeVersionThe active Unicode provider version.
provider.versionVersion identifier.
provider.wcwidth(codepoint)Width of a code point: 0, 1, or 2 cells.
provider.charProperties(codepoint, preceding)Calculate packed character properties.

IModes (read-only)

Public itemDescription
applicationCursorKeysModeApplication cursor keys setting.
applicationKeypadModeApplication keypad setting.
bracketedPasteModeBracketed-paste setting.
insertModeInsert-mode setting.
mouseTrackingModeMouse reporting: 'none', 'x10', 'vt200', 'drag', or 'any'.
originModeOrigin mode setting.
reverseWraparoundModeReverse wraparound setting.
sendFocusModeFocus event reporting setting.
synchronizedOutputModeSynchronized output setting.
wraparoundModeLine wraparound setting.

Links, Markers, and Decorations

Link providers and decorations are optional extension points. registerDecoration() and other experimental members require proposed API access. A marker can become invalid when its buffer line scrolls out of history.

ILinkProvider and ILink

Public itemDescription
provideLinks(bufferLineNumber, callback)Find links at a buffer line and return an ILink[] or undefined through a callback.
ILink.rangeStart and end cell positions of the link.
ILink.textLink text.
ILink.decorationsOptional pointer and underline controls.
ILink.activate(event, text)Activation callback.
ILink.hover(event, text)Optional hover callback.
ILink.leave(event, text)Optional leave callback.
ILink.dispose()Optional cleanup callback.
ILinkDecorations.pointerCursorWhether link hover uses a pointer cursor.
ILinkDecorations.underlineWhether a detected link appears underlined.
IBufferRange.startStart cell position.
IBufferRange.endEnd cell position.
IBufferCellPosition.xCell column.
IBufferCellPosition.yCell row.
IViewportRange.startStart viewport position.
IViewportRange.endEnd viewport position.
IViewportRangePosition.xViewport column.
IViewportRangePosition.yViewport row.

Marker and decoration objects

Public itemDescription
IMarker.idUnique marker identifier.
IMarker.lineCurrent buffer line of a marker.
IMarker.onDispose(listener)Callback when the marker is disposed.
IMarker.isDisposedWhether the marker has been disposed.
IMarker.dispose()Release the marker.
IDecoration.markerAssociated marker.
IDecoration.elementRendered decoration element, initially undefined.
IDecoration.onRender(listener)Receive the decoration DOM element after rendering.
IDecoration.optionsEditable overviewRulerOptions when enabled on creation.
IDecoration.onDispose(listener)Callback when a decoration is disposed.
IDecoration.isDisposedWhether the decoration is disposed.
IDecoration.dispose()Remove the decoration.
IDisposable.dispose()Release a disposable resource.
IDisposableWithEvent.onDispose(listener)Subscribe to resource disposal.
IDisposableWithEvent.isDisposedRead the resource’s disposal state.
IEvent(listener)Subscribe to an event and receive an IDisposable.

IDecorationOptions

Public itemDescription
markerRequired marker associated with the decoration.
anchorAnchor side: 'left' or 'right'.
xHorizontal character-cell offset.
widthDecoration width in cells.
heightDecoration height in cells.
backgroundColorDecoration background color.
foregroundColorDecoration foreground color.
layerDecoration layer: 'bottom' or 'top'.
overviewRulerOptionsOptional IDecorationOverviewRulerOptions.

IDecorationOverviewRulerOptions

Public itemDescription
colorRequired overview ruler mark color.
positionPosition: 'left', 'center', 'right', or 'full'.

Localization and addon contract

Public itemDescription
Terminal.strings.promptLabelText label for the accessible prompt.
Terminal.strings.tooMuchOutputLocalized label for excessive output.
ITerminalAddon.activate(terminal)Initialize a custom addon with the host terminal.
ITerminalAddon.dispose()Release an addon and its event subscriptions.
IBufferElementProvider.provideBufferElements()Produce buffer DOM elements for consumers of this extension API.

Official Addons

Addon packages

Public itemDescription
@xterm/addon-attachConnect terminal input and output to a WebSocket. Authentication, authorization, and session security belong to the application.
@xterm/addon-clipboardAccess the browser clipboard.
@xterm/addon-fitCalculate terminal columns and rows from its container.
@xterm/addon-imageDisplay supported inline images.
@xterm/addon-ligaturesRender font ligatures.
@xterm/addon-progressProcess terminal progress sequences using OSC 9;4.
@xterm/addon-searchSearch terminal buffer content.
@xterm/addon-serializeSerialize buffer state as terminal escape sequences or HTML.
@xterm/addon-unicode-graphemesExperimental grapheme-aware Unicode handling.
@xterm/addon-unicode11Use Unicode 11 character widths.
@xterm/addon-web-fontsIntegrate web fonts.
@xterm/addon-web-linksDetect and interact with links.
@xterm/addon-webglRender terminal glyphs through WebGL2.

Alternatives & Related Resources

FAQs

Q: Why does my xterm.js terminal appear blank or render incorrectly?

A: Confirm that xterm.css loaded and the container has a measurable width and height. Run open() after the element becomes visible, then call fit() if you use the Fit addon.

Q: Can I use xterm.js in a React or Vue application?

A: Yes. Initialize Terminal after the container element mounts, retain the instance between component updates, and call dispose() during unmount cleanup. Disconnect any ResizeObserver used for fitting.

Q: How should WebSocket connections handle binary terminal input?

A: Forward onData text using UTF-8 and convert onBinary strings into raw bytes. The backend must distinguish text and binary frames before forwarding their contents to the PTY.

Q: How do I turn on screen reader support?

A: Set screenReaderMode: true and consider minimumContrastRatio for foreground contrast. Screen reader support includes additional DOM elements for NVDA on Windows and VoiceOver on macOS. Test your application with assistive technology.

Q: How can I restore a terminal display after reconnection?

A: @xterm/addon-serialize can capture terminal buffer content for replay into a new terminal instance. The backend must preserve or restore the actual shell session separately.

You Might Be Interested In:


Leave a Reply