termcast

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

chromedp logo

About termcast

termcast is a small Go package that streams the screen of a chromedp page to a terminal that has graphics. It uses the screencast of the Chrome DevTools Protocol to get the frames, and rasterm to draw them. It works in Kitty, iTerm2 and Sixel terminals. You start it with one call, and on a Kitty terminal it draws the frames with no flicker.

Unit Tests Go Reference Releases Discord Discussion

Install

The module needs Go 1.25 or later. It requires chromedp v0.23.1, cdproto v0.160.1 and rasterm v0.3.1.

go get github.com/chromedp/termcast

Usage

Load the page first, so that the stream has a page to show. Start also starts the browser when the context has none. The stream stops when you call Stop, and when the context ends.

The program owns its flags. Start the stream only when the flag of the program asks for it. A nil *Stream is a stream that is off, and its methods are safe, so the program calls Stop and LogWriter in either case.

package main

import (
	"context"
	"flag"
	"log"
	"time"

	"github.com/chromedp/chromedp"
	"github.com/chromedp/termcast"
)

func main() {
	onTerminal := flag.Bool("visible-on-terminal", false, "draw the page in the terminal")
	fps := flag.Float64("terminal-fps", termcast.DefaultFPS, "frames per second of the stream")
	flag.Parse()

	ctx, cancel := chromedp.NewContext(context.Background())
	defer cancel()

	// Load the page. This call starts the browser.
	if err := chromedp.Do(ctx, chromedp.Navigate("https://example.com")); err != nil {
		log.Fatal(err)
	}

	var s *termcast.Stream
	if *onTerminal {
		var err error
		if s, err = termcast.Start(ctx, termcast.WithFPS(*fps)); err != nil {
			log.Fatal(err)
		}
	}
	defer s.Stop()
	log.SetOutput(s.LogWriter())

	log.Println("the page is on the screen")
	if err := chromedp.Do(ctx, chromedp.Sleep(10*time.Second)); err != nil {
		// log.Fatal skips the deferred calls, so stop the stream first.
		s.Stop()
		log.Fatal(err)
	}
}

Run it with the flag:

go run . -visible-on-terminal

How it works

Start asks the terminal which graphics protocols it has, with rasterm.Detect. Then it starts the screencast of the page.

The browser sends a frame only when the page changes. The stream keeps the latest frame and draws it at each tick, but only when the frame is new. A page that stops changing stays on the screen. A program can end before the browser sends the first frame. In that case Stop takes one screenshot, so that the final frame is never empty.

The stream draws a frame in one of two ways:

  1. On a Kitty terminal that plays animations, it draws each frame into one Kitty image with rasterm.KittyStream. The picture changes at once, with no clear and no flicker. When the size of the frame changes, the stream deletes the image, clears the screen once and starts a new image.
  2. On other terminals, it clears the screen with \x1b[H\x1b[2J and draws the frame.

The stream uses no alternate screen and does not hide the cursor. A program that ends with log.Fatal skips its deferred calls, and the terminal must not stay in a changed state. See the decision and the decision for the new API.

Options

Option Default Meaning
WithFPS(fps) 4 The most frames per second that the stream draws
WithQuality(q) 80 The JPEG quality of the frames, from 0 to 100
WithMaxSize(w, h) 1024 by 768 The largest size of a frame in pixels
WithOutput(w) os.Stdout The writer that receives the frames
WithLogOutput(w) os.Stderr The writer that receives the held log lines
WithElement(sel) the whole page Draws only the element that the selector finds
WithTerminal(t) detection The rasterm.Terminal to draw on, with no detection
WithDetectOptions(opts...) none The options of rasterm.Detect, such as a timeout
WithAnimation(on) the terminal decides Turns the Kitty stream on or off

Programs that use it

The chromedp/examples repository has 34 programs that use termcast. Most of them take the flags -visible-on-terminal and -terminal-fps, which a small helper of that repository defines. The program termcast calls Start directly. It plays an animated SVG and streams it to the terminal. These programs use the package: click, console, cookie, dialogs, download_file, download_image, dragdrop, emulate, eval, eventsiter, exposefunc, extension, fast, forecast, frames, geoip, headers, intercept, keys, latlon, logic, pdf, pdfoptions, proxy, remote, screenshot, selectors, structeval, submit, subtree, termcast, text, upload and visible.

Show one element

WithElement takes a chromedp selector, such as chromedp.CSS("#chart"), and draws only the first element that it matches.

s, err := termcast.Start(ctx, termcast.WithElement(chromedp.CSS("#chart")))

The stream looks up the element again at each frame, so an element that moves or changes its size stays in view. It crops the frame to the border box of the element. The browser sends the viewport, so the stream shows the part of the element that is in the viewport. Use chromedp.ScrollIntoView first when the element is lower on the page. While the page has no such element, the stream keeps what is on the screen.

Terminals that work

The terminal must support one of these graphics protocols:

  • Kitty and Ghostty
  • iTerm2, WezTerm and mintty
  • Sixel

Start calls rasterm.Detect. It asks the terminal with a query, and reads the environment when the terminal does not answer. The variable TERM_GRAPHICS forces the protocol to kitty, iterm, sixel or halfblock, and the value none turns graphics off. Start returns ErrNoGraphics when no protocol is available.

The query reads the input of the terminal. When the user types while Start waits for the answer, Stream.Keys returns those keys. A program that reads its input must use them as its first input. Stream.Terminal returns what detection found.

To skip detection, give the terminal with WithTerminal. Use it when the output is not the terminal, for example when the frames go to a file:

s, err := termcast.Start(ctx,
	termcast.WithOutput(f),
	termcast.WithTerminal(rasterm.Terminal{Protocol: rasterm.Kitty}),
)

The Kitty stream needs a terminal that plays Kitty animations. By default the stream uses it when the terminal reports that it plays them, or names itself kitty or Ghostty. Other terminals that draw Kitty images get a clear at each frame. WithAnimation(true) forces the Kitty stream, and WithAnimation(false) turns it off.

Log lines

A log line that the program prints draws over the frames. Stream.LogWriter returns a writer that holds the lines while the stream runs. When the stream stops, it draws a final frame and then prints the lines to the log output. Use log.SetOutput(s.LogWriter()). After Stop, the writer passes each line on at once.

log.Fatal ends the program before a deferred Stop runs. So call s.Stop() before log.Fatal, and the final frame and the held lines reach the terminal. Stop returns the first error that the stream met.

Every method of *Stream is safe on a nil pointer. On a nil stream, Stop does nothing and returns nil, LogWriter returns os.Stderr, Terminal returns the zero rasterm.Terminal and Keys returns nil.

Other output

Output that draws over the frames does not work together with the stream. An example is the protocol messages of chromedp.WithDebugf, which the flag -v of the examples turns on. The program decides which one it shows. The examples stop with an error when both flags are on.

Tests

The tests start Chrome and need no terminal. They give the terminal with WithTerminal, use a fake encoder or a buffer, and load a local page that animates. See AGENTS.md for the commands.

GOWORK=off go test -race ./...

Contributing

See CONTRIBUTING.md. Ask questions in the GitHub Discussions of chromedp, and report bugs in the issues of chromedp. The documents of this repository are AGENTS.md, CLAUDE.md, CONTRIBUTING.md and docs/decisions/README.md.

Documentation

Overview

Package termcast streams the screen of a chromedp page to a terminal that has graphics.

It uses the screencast of the Chrome DevTools Protocol to get the frames of the page, and the package rasterm to draw them. Start asks the terminal which graphics it has, with rasterm.Detect. The terminal must support Kitty, iTerm2 or Sixel graphics. Start returns ErrNoGraphics when it does not.

The browser sends a frame only when the page changes. The stream keeps the latest frame and draws it again only when it is new, so a page that stops changing stays on the screen. On a Kitty terminal that plays animations, the stream draws each frame into one Kitty image, so the picture changes with no flicker. See WithAnimation. On other terminals, the stream clears the screen at each redraw and draws the latest frame. It uses no alternate screen and does not hide the cursor. A program that ends with log.Fatal skips its deferred calls, so the stream must never leave the terminal in a changed state.

The log lines of the program draw over the frames. Stream.LogWriter holds the lines while the stream runs and prints them when the stream stops, after a final frame. Other output that draws over the frames, such as the protocol messages of chromedp.WithDebugf, does not work together with the stream. The program decides which one it shows.

A nil *Stream is a stream that is off, and its methods are safe. So a program starts the stream only when its own flag asks for it, and writes defer s.Stop() and log.SetOutput(s.LogWriter()) in either case. See the example.

Example

A program has its own flag for the stream, and starts the stream only when the flag is on. A nil stream is a stream that is off, so the program calls Stop and LogWriter in either case.

package main

import (
	"context"
	"flag"
	"log"
	"time"

	"github.com/chromedp/chromedp"
	"github.com/chromedp/termcast"
)

func main() {
	onTerminal := flag.Bool("visible-on-terminal", false, "draw the page in the terminal")
	fps := flag.Float64("terminal-fps", termcast.DefaultFPS, "frames per second of the stream")
	flag.Parse()

	ctx, cancel := chromedp.NewContext(context.Background())
	defer cancel()

	// Load the page. This call starts the browser.
	if err := chromedp.Do(ctx, chromedp.Navigate("https://example.com")); err != nil {
		log.Fatal(err)
	}

	// Start the stream. Start returns termcast.ErrNoGraphics for a terminal
	// that has no graphics.
	var s *termcast.Stream
	if *onTerminal {
		var err error
		if s, err = termcast.Start(ctx, termcast.WithFPS(*fps)); err != nil {
			log.Fatal(err)
		}
	}
	defer s.Stop()
	// The log lines wait until the stream stops, so that they do not draw over
	// the frames.
	log.SetOutput(s.LogWriter())

	log.Println("the page is on the screen")
	if err := chromedp.Do(ctx, chromedp.Sleep(5*time.Second)); err != nil {
		// log.Fatal skips the deferred calls. Stop first, so that the final
		// frame and the held log lines reach the terminal.
		s.Stop()
		log.Fatal(err)
	}
}

Index

Examples

Constants

View Source
const (
	// DefaultFPS is the number of frames per second that the stream draws.
	DefaultFPS = 4
	// DefaultQuality is the JPEG quality that the screencast asks for.
	DefaultQuality = 80
	// DefaultWidth is the largest width of a frame in pixels.
	DefaultWidth = 1024
	// DefaultHeight is the largest height of a frame in pixels.
	DefaultHeight = 768
)

Default values of the options.

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error string

Error is the type of the constant errors of this package.

const (
	// ErrNoGraphics is the error that [Start] returns when the terminal has no
	// graphics. [rasterm.Detect] finds Kitty, iTerm2 and Sixel from a query to
	// the terminal and from the environment. The variable TERM_GRAPHICS can force
	// the type to kitty, iterm or sixel, and the value none turns graphics
	// off.
	ErrNoGraphics Error = "" /* 131-byte string literal not displayed */
)

func (Error) Error

func (err Error) Error() string

Error satisfies the [error] interface.

type Option

type Option func(*config)

Option changes how Start makes a stream.

func WithAnimation added in v0.3.0

func WithAnimation(on bool) Option

WithAnimation turns the Kitty stream on or off. The Kitty stream draws each frame into one Kitty image with rasterm.KittyStream, so it does not clear the screen and does not flicker. It works only with the Kitty protocol.

By default, the stream uses it when the terminal reports that it plays a Kitty animation, or when it names itself kitty or Ghostty. A terminal that draws Kitty images but has no animation shows only the first frame of a Kitty stream, so the default does not guess.

func WithDetectOptions added in v0.3.0

func WithDetectOptions(opts ...rasterm.DetectOption) Option

WithDetectOptions gives options to rasterm.Detect, such as rasterm.WithTimeout. WithTerminal turns detection off, and then the options do nothing.

func WithElement added in v0.2.0

func WithElement[S chromedp.Selectable](sel S) Option

WithElement makes the stream draw only the element that sel selects, and not the whole page. The element is the first one that the selector matches, for example chromedp.CSS("#chart"). The stream looks the element up again at each frame, so an element that moves or changes its size stays in view.

The browser sends the viewport, so the stream shows the part of the element that is in the viewport. Scroll the element into view first, for example with chromedp.ScrollIntoView. While the page has no such element, the stream keeps what is on the screen.

func WithFPS

func WithFPS(fps float64) Option

WithFPS sets the number of frames per second that the stream draws at most. The default is DefaultFPS.

func WithLogOutput

func WithLogOutput(w io.Writer) Option

WithLogOutput sets the writer that receives the held log lines when the stream stops. The default is os.Stderr.

func WithMaxSize

func WithMaxSize(width, height int) Option

WithMaxSize sets the largest width and height of a frame in pixels. The browser scales a larger page down. The default is DefaultWidth by DefaultHeight.

func WithOutput

func WithOutput(w io.Writer) Option

WithOutput sets the writer that receives the frames. The default is os.Stdout. Detection asks the terminal on os.Stdout and os.Stdin, so give WithTerminal too when w is not that terminal.

func WithQuality

func WithQuality(quality int) Option

WithQuality sets the JPEG quality of the frames that the browser sends, from 0 to 100. The default is DefaultQuality.

func WithTerminal added in v0.3.0

func WithTerminal(t rasterm.Terminal) Option

WithTerminal makes Start use t, and not detect the terminal. Use it when the program detected the terminal itself, or when the output is not the terminal, for example rasterm.Terminal{Protocol: rasterm.Kitty} for a file. Start returns ErrNoGraphics when t.Protocol is rasterm.None.

type Stream

type Stream struct {
	// contains filtered or unexported fields
}

Stream draws the screen of a page in the terminal. Start makes it. A nil stream is a stream that is off. Every method is safe on a nil pointer, and safe to call from several goroutines.

func Start

func Start(ctx context.Context, opts ...Option) (*Stream, error)

Start starts the screencast of the page of ctx and draws it in the terminal. The context is a chromedp context. Start starts the browser and opens the target when the context has none yet, as chromedp.Run does.

Start first detects the terminal with rasterm.Detect, unless WithTerminal gives it. It returns ErrNoGraphics when the terminal has no graphics. The stream ends when the context ends, and then it acts as Stream.Stop.

func (*Stream) Keys added in v0.3.0

func (s *Stream) Keys() []byte

Keys returns the keys that the user typed while Start detected the terminal, in the order of the typing. Detection reads the input to get the answers of the terminal, so a program that reads its input must use these keys as its first input. It returns nil on a nil stream, and when WithTerminal turned detection off.

func (*Stream) LogWriter

func (s *Stream) LogWriter() io.Writer

LogWriter returns a writer for the log lines of the program, for example for log.SetOutput. While the stream runs, the writer holds the lines in memory. Stream.Stop prints them to the log output after the final frame. After Stream.Stop, the writer passes each line on at once. On a nil stream, it returns os.Stderr.

func (*Stream) Stop

func (s *Stream) Stop() error

Stop stops the screencast and the goroutines of the stream, draws the final frame once, and then prints the held log lines. When no frame arrived, it takes one screenshot as the final frame. It returns the first error that the stream met, such as an error of the encoder or of the output.

Stop is safe to call more than once and from several goroutines. Each call returns the same error. A call that arrives while another one runs waits until that one is done. The stream also stops by itself when the context of Start ends. On a nil stream, Stop does nothing and returns nil.

func (*Stream) Terminal added in v0.3.0

func (s *Stream) Terminal() rasterm.Terminal

Terminal returns the terminal that the stream draws on, as rasterm.Detect found it or as WithTerminal gave it. On a nil stream, it returns the zero rasterm.Terminal, which has no graphics.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址