
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 asfontWeight.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):IThemecolors for text, cursor, selection, and ANSI palette.allowTransparency(boolean): Permit transparent backgrounds. Set beforeopen(). 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):ILinkHandlerfor 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. Set0for instant scrolling.
Integration and advanced behavior
allowProposedApi(boolean): Enable experimental APIs. Default:false.documentOverride(any | null): Use a specificDocumentfor multi-window integrations.logLevel(LogLevel): Logging threshold:'trace','debug','info','warn','error', or'off'. Default:'info'.logger(ILogger | null):ILoggerimplementation used in place ofconsole.overviewRuler(IOverviewRulerOptions):IOverviewRulerOptionsfor the overview ruler.windowOptions(IWindowOptions):IWindowOptionsfor terminal-initiated window operations and reports. Disabled by default.windowsPty(IWindowsPty):IWindowsPtysettings for Windows PTY behavior.
Initialization-only dimensions
| Public item | Description |
|---|---|
cols | Initial terminal column count. |
rows | Initial terminal row count. |
Theme Colors
Set the following ITheme properties inside theme.
Base, selection, and scroll bar colors
| Public item | Description |
|---|---|
foreground | Default foreground color. |
background | Default background color. |
cursor | Cursor color. |
cursorAccent | Foreground color inside a block cursor. |
selectionBackground | Background color of selected text. |
selectionForeground | Optional text color for selections. |
selectionInactiveBackground | Selection color while the terminal lacks focus. |
scrollbarSliderBackground | Scroll bar thumb at rest. |
scrollbarSliderHoverBackground | Scroll bar thumb on hover. |
scrollbarSliderActiveBackground | Scroll bar thumb when active. |
overviewRulerBorder | Border color beside the overview ruler. |
ANSI palette
| Public item | Description |
|---|---|
black | ANSI black. |
red | ANSI red. |
green | ANSI green. |
yellow | ANSI yellow. |
blue | ANSI blue. |
magenta | ANSI magenta. |
cyan | ANSI cyan. |
white | ANSI white. |
brightBlack | Bright ANSI black. |
brightRed | Bright ANSI red. |
brightGreen | Bright ANSI green. |
brightYellow | Bright ANSI yellow. |
brightBlue | Bright ANSI blue. |
brightMagenta | Bright ANSI magenta. |
brightCyan | Bright ANSI cyan. |
brightWhite | Bright ANSI white. |
extendedAnsi | Array 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 item | Description |
|---|---|
width | Overview ruler width in pixels. |
showTopBorder | Display the top border. |
showBottomBorder | Display the bottom border. |
IWindowsPty
| Public item | Description |
|---|---|
backend | Backend type: 'conpty' or 'winpty'. |
buildNumber | Windows build number for compatibility behavior. |
ILogger callbacks
| Public item | Description |
|---|---|
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 item | Description |
|---|---|
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. |
allowNonHttpProtocols | Explicitly opt in to hyperlinks with non-HTTP(S) protocols. Validate untrusted URLs first. |
IWindowOptions permissions
| Public item | Description |
|---|---|
restoreWin | Allow restoring the window. |
minimizeWin | Allow minimizing the window. |
setWinPosition | Allow changing its pixel position. |
setWinSizePixels | Allow changing its pixel dimensions. |
raiseWin | Allow raising the window. |
lowerWin | Allow lowering the window. |
refreshWin | Allow requests to refresh the window. |
setWinSizeChars | Allow changing dimensions in terminal cells. |
maximizeWin | Allow maximizing the window. |
fullscreenWin | Allow fullscreen requests. |
getWinState | Allow window state reports. |
getWinPosition | Allow window position reports. |
getWinSizePixels | Allow window size reports in pixels. |
getScreenSizePixels | Allow screen size reports in pixels. |
getCellSizePixels | Allow character cell size reports in pixels. |
getWinSizeChars | Allow window size reports in terminal cells. |
getScreenSizeChars | Allow screen size reports in terminal cells. |
getIconTitle | Allow icon title reports. |
getWinTitle | Allow window title reports. |
pushTitle | Allow pushing a title onto the title stack. |
popTitle | Allow popping the previously saved title. |
setWinLines | Allow 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 item | Description |
|---|---|
element | Rendered terminal root element, or undefined before opening. |
textarea | Input textarea, or undefined before opening. |
cols | Current viewport column count (read-only). |
rows | Current viewport row count (read-only). |
options | Readable and writable terminal option collection. |
buffer | IBufferNamespace for normal, alternate, and active buffers. |
markers | Registered markers (experimental). |
modes | Read-only terminal modes updated by terminal sequences. |
parser | Escape-sequence parser registration API. |
unicode | Unicode version API (experimental). |
Terminal.strings | Static ILocalizableStrings object. |
Terminal events
| Public item | Description |
|---|---|
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 item | Description |
|---|---|
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 item | Description |
|---|---|
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 item | Description |
|---|---|
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 item | Description |
|---|---|
active | Current normal or alternate buffer. |
normal | Normal buffer. |
alternate | Alternate-screen buffer. |
onBufferChange(listener) | Event fired when the active buffer changes. |
IBuffer
| Public item | Description |
|---|---|
type | Buffer kind: 'normal' or 'alternate'. |
cursorX | Cursor column relative to the viewport. |
cursorY | Cursor row relative to the viewport. |
viewportY | First buffer line in the current viewport. |
baseY | First line of the bottommost viewport. |
length | Total buffer line count. |
getLine(y) | Read an IBufferLine or undefined at a zero-based buffer index. |
getNullCell() | Create a reusable blank IBufferCell. |
IBufferLine
| Public item | Description |
|---|---|
isWrapped | Whether this line continues a wrapped line. |
length | Number 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 item | Description |
|---|---|
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 item | Description |
|---|---|
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 item | Description |
|---|---|
prefix | Optional sequence prefix. |
intermediates | Optional intermediate bytes. |
final | Required final character. |
Unicode extension API (experimental)
| Public item | Description |
|---|---|
unicode.register(provider) | Register an IUnicodeVersionProvider. |
unicode.versions | Available Unicode provider versions. |
unicode.activeVersion | The active Unicode provider version. |
provider.version | Version 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 item | Description |
|---|---|
applicationCursorKeysMode | Application cursor keys setting. |
applicationKeypadMode | Application keypad setting. |
bracketedPasteMode | Bracketed-paste setting. |
insertMode | Insert-mode setting. |
mouseTrackingMode | Mouse reporting: 'none', 'x10', 'vt200', 'drag', or 'any'. |
originMode | Origin mode setting. |
reverseWraparoundMode | Reverse wraparound setting. |
sendFocusMode | Focus event reporting setting. |
synchronizedOutputMode | Synchronized output setting. |
wraparoundMode | Line 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 item | Description |
|---|---|
provideLinks(bufferLineNumber, callback) | Find links at a buffer line and return an ILink[] or undefined through a callback. |
ILink.range | Start and end cell positions of the link. |
ILink.text | Link text. |
ILink.decorations | Optional 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.pointerCursor | Whether link hover uses a pointer cursor. |
ILinkDecorations.underline | Whether a detected link appears underlined. |
IBufferRange.start | Start cell position. |
IBufferRange.end | End cell position. |
IBufferCellPosition.x | Cell column. |
IBufferCellPosition.y | Cell row. |
IViewportRange.start | Start viewport position. |
IViewportRange.end | End viewport position. |
IViewportRangePosition.x | Viewport column. |
IViewportRangePosition.y | Viewport row. |
Marker and decoration objects
| Public item | Description |
|---|---|
IMarker.id | Unique marker identifier. |
IMarker.line | Current buffer line of a marker. |
IMarker.onDispose(listener) | Callback when the marker is disposed. |
IMarker.isDisposed | Whether the marker has been disposed. |
IMarker.dispose() | Release the marker. |
IDecoration.marker | Associated marker. |
IDecoration.element | Rendered decoration element, initially undefined. |
IDecoration.onRender(listener) | Receive the decoration DOM element after rendering. |
IDecoration.options | Editable overviewRulerOptions when enabled on creation. |
IDecoration.onDispose(listener) | Callback when a decoration is disposed. |
IDecoration.isDisposed | Whether the decoration is disposed. |
IDecoration.dispose() | Remove the decoration. |
IDisposable.dispose() | Release a disposable resource. |
IDisposableWithEvent.onDispose(listener) | Subscribe to resource disposal. |
IDisposableWithEvent.isDisposed | Read the resource’s disposal state. |
IEvent(listener) | Subscribe to an event and receive an IDisposable. |
IDecorationOptions
| Public item | Description |
|---|---|
marker | Required marker associated with the decoration. |
anchor | Anchor side: 'left' or 'right'. |
x | Horizontal character-cell offset. |
width | Decoration width in cells. |
height | Decoration height in cells. |
backgroundColor | Decoration background color. |
foregroundColor | Decoration foreground color. |
layer | Decoration layer: 'bottom' or 'top'. |
overviewRulerOptions | Optional IDecorationOverviewRulerOptions. |
IDecorationOverviewRulerOptions
| Public item | Description |
|---|---|
color | Required overview ruler mark color. |
position | Position: 'left', 'center', 'right', or 'full'. |
Localization and addon contract
| Public item | Description |
|---|---|
Terminal.strings.promptLabel | Text label for the accessible prompt. |
Terminal.strings.tooMuchOutput | Localized 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 item | Description |
|---|---|
@xterm/addon-attach | Connect terminal input and output to a WebSocket. Authentication, authorization, and session security belong to the application. |
@xterm/addon-clipboard | Access the browser clipboard. |
@xterm/addon-fit | Calculate terminal columns and rows from its container. |
@xterm/addon-image | Display supported inline images. |
@xterm/addon-ligatures | Render font ligatures. |
@xterm/addon-progress | Process terminal progress sequences using OSC 9;4. |
@xterm/addon-search | Search terminal buffer content. |
@xterm/addon-serialize | Serialize buffer state as terminal escape sequences or HTML. |
@xterm/addon-unicode-graphemes | Experimental grapheme-aware Unicode handling. |
@xterm/addon-unicode11 | Use Unicode 11 character widths. |
@xterm/addon-web-fonts | Integrate web fonts. |
@xterm/addon-web-links | Detect and interact with links. |
@xterm/addon-webgl | Render terminal glyphs through WebGL2. |
Alternatives & Related Resources
- Emulating A Shell Environment With The ttty.js Library
- Vanilla JavaScript Shell Terminal Emulator With Async/Await Functions – jsShell.js
- Cross-platform Terminal Emulator In Vanilla JavaScript – vanilla-terminal
- Lightweight Terminal Emulator With Vanilla JavaScript – Jaxit
- Minimal Interactive Terminal In JavaScript – Terminal.js
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.







