browser

package
v0.0.0-...-d2ee020 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: LGPL-2.1, LGPL-2.1-or-later Imports: 32 Imported by: 0 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.

Documentation

Overview

Package browser drives a headless Chrome through the DevTools Protocol with chromedp: it sizes the viewport to the grid, injects the BlankMono grid stylesheet in every document, takes screenshots and runs the text walker.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Browser

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

Browser is one Chrome tab.

func New

func New(ctx context.Context, opts Options) (*Browser, error)

New starts Chrome and prepares the tab. ctx bounds the whole lifetime. A profile directory is used by one Chrome at a time, so when a second session finds it taken the browser falls back to a throwaway profile rather than refusing to start.

func (*Browser) Back

func (b *Browser) Back() error

Back goes one step back in the tab history.

func (*Browser) Blur

func (b *Browser) Blur() error

Blur removes focus from the active element, leaving input mode.

func (*Browser) Capture

func (b *Browser) Capture(withText bool) (Page, error)

Capture reads the page, retrying when the layout changes in between so every layer describes the same geometry. The interface renderer takes no screenshot: its frames, widgets and text all come from one snapshot.

func (*Browser) Click

func (b *Browser) Click(col, row int) error

Click sends a left click at the center of a cell. The events carry a mouse pointer type and the button bitmask, so the pointerdown, pointerup and click a modern player listens for are all generated; without the bitmask the pointer events say no button is down and the player ignores them. Call WaitSettled afterwards: the click may start a navigation.

func (*Browser) Close

func (b *Browser) Close() error

Close shuts Chrome down.

func (*Browser) ConsentReloaded

func (b *Browser) ConsentReloaded() bool

ConsentReloaded reports whether answering the last banner made the page load a new document, which then has to be waited for like the first one.

func (*Browser) Context

func (b *Browser) Context() context.Context

Context is the tab's chromedp context, for callers that need raw CDP.

func (*Browser) CropCells

func (b *Browser) CropCells(x, y, w, h int) (image.Image, error)

CropCells photographs one rectangle of cells and returns it scaled to the pixels those cells average over. It is how a live video is refreshed without recapturing the page.

func (*Browser) DismissConsent

func (b *Browser) DismissConsent(prefer string, max time.Duration) ([]string, error)

DismissConsent answers the cookie or privacy banner, if there is one: it looks in every frame, consent managers usually live in an iframe of their own, and clicks the refusal, or the acceptance when prefer is "accept" or when there is no refusal to click. Banners that come in two steps get a second round. It returns the labels it clicked.

func (*Browser) FollowReload

func (b *Browser) FollowReload(seq int64, max time.Duration) bool

FollowReload waits for the new document when something since seq, typically a click, made the page navigate or reload itself: answering a consent banner often does. Counters rather than a signal, so a document that was ready before the wait began is not waited for again. It returns whether a new document came.

func (*Browser) Forward

func (b *Browser) Forward() error

Forward goes one step forward in the tab history.

func (*Browser) Grid

func (b *Browser) Grid() grid.Grid

Grid returns the current viewport grid.

func (*Browser) InsertText

func (b *Browser) InsertText(s string) error

InsertText types text into the focused element, as an IME would.

func (*Browser) Key

func (b *Browser) Key(key string) error

Key sends one key press (keyDown, keyUp) for a key from the kb package, such as kb.Enter or kb.Backspace. Call WaitSettled afterwards when the key may submit a form.

func (*Browser) NavSeq

func (b *Browser) NavSeq() int64

NavSeq counts the documents the main frame has started loading.

func (*Browser) Navigate

func (b *Browser) Navigate(url string) error

Navigate loads a URL and waits for its load event (or the timeout).

func (*Browser) PrepareMedia

func (b *Browser) PrepareMedia(timeout time.Duration) (MediaPrep, error)

PrepareMedia loads lazy images and starts videos, waiting at most timeout for the images to arrive.

func (*Browser) ProfileNote

func (b *Browser) ProfileNote() string

ProfileNote is non-empty when the wanted profile could not be used.

func (*Browser) Reload

func (b *Browser) Reload() error

Reload reloads the page and waits for it to settle.

func (*Browser) Resize

func (b *Browser) Resize(g grid.Grid) error

Resize changes the viewport to match a new grid. A running screencast is restarted at the new size.

func (*Browser) Screenshot

func (b *Browser) Screenshot() (image.Image, error)

Screenshot captures the viewport, exactly the grid's pixel size. Up to maxShotPixels it is one capture, returned as decoded. Beyond that the viewport is captured in vertical tiles, each a whole number of grid rows, through the clip parameter (CSS pixels), and stitched into one grayscale image holding the Rec. 709 luma of every pixel: one byte per pixel keeps a 6400 x 60000 page under 400 MB.

func (*Browser) ScrollBy

func (b *Browser) ScrollBy(deltaRows int) error

ScrollBy scrolls the window by deltaRows rows, positive down.

func (*Browser) ScrollHeight

func (b *Browser) ScrollHeight() (int, error)

ScrollHeight returns the full document height in CSS pixels.

func (*Browser) ScrollTo

func (b *Browser) ScrollTo(bottom bool) error

ScrollTo scrolls to the top or the bottom of the document.

func (*Browser) ScrollToRow

func (b *Browser) ScrollToRow(row int) error

ScrollToRow scrolls the window so that the given grid row is at the top of the viewport.

func (*Browser) SetScreenRows

func (b *Browser) SetScreenRows(n int)

SetScreenRows tells the browser how tall one screenful is, which is what the "auto" renderer weighs against the frame height.

func (*Browser) SnapshotRuns

func (b *Browser) SnapshotRuns() ([]frame.TextRun, error)

SnapshotRuns extracts the page text with DOMSnapshot.captureSnapshot instead of measuring it in the page. The snapshot already flattens shadow trees and slots, gives one box per rendered line with its offset into the layout text, and a global paint order that decides occlusion, so no per-character measuring and no hit testing are needed.

func (*Browser) SnapshotUI

func (b *Browser) SnapshotUI() ([]frame.TextRun, []frame.UIBox, error)

SnapshotUI extracts the page text and the interface layer in one capture: container frames, form widgets and media placeholders.

func (*Browser) StartScreencast

func (b *Browser) StartScreencast() (<-chan *ScreencastFrame, error)

StartScreencast asks Chrome to push a frame whenever the page repaints, as JPEG at the grid's pixel size when that is within Chrome's cap, else as a thumbnail that serves as a change notification. Frames arrive on the returned channel, which holds one frame: a frame that is still waiting when the next arrives is dropped and acknowledged together with the newer one, so the receiver always sees the latest and Chrome never runs ahead. Call StopScreencast, or Resize, which restarts it at the new size.

func (*Browser) StartVideo

func (b *Browser) StartVideo(opts VideoOptions) error

StartVideo installs the in-page video renderer and points it at the current grid. It is safe to call again: the page reconfigures itself and picks up videos that appeared since.

func (*Browser) State

func (b *Browser) State() (PageState, error)

State reads the current PageState.

func (*Browser) StopScreencast

func (b *Browser) StopScreencast() error

StopScreencast stops the frame stream.

func (*Browser) TextRuns

func (b *Browser) TextRuns() ([]frame.TextRun, error)

TextRuns reads the page text with the configured source.

func (*Browser) Title

func (b *Browser) Title() (string, error)

Title returns the current document title.

func (*Browser) URL

func (b *Browser) URL() (string, error)

URL returns the current document URL.

func (*Browser) VideoFrames

func (b *Browser) VideoFrames() <-chan VideoFrame

VideoFrames is where rendered video frames arrive. The channel holds one frame per video box: a frame that is still waiting when a newer one comes in is dropped, because only the latest is worth drawing.

func (*Browser) VideoInterval

func (b *Browser) VideoInterval() time.Duration

VideoInterval is the shortest gap between refreshes of a live video.

func (*Browser) VideoMode

func (b *Browser) VideoMode() string

VideoMode reports how videos are drawn.

func (*Browser) VideoStatus

func (b *Browser) VideoStatus() string

VideoStatus reports what the last injection did, for the log.

func (*Browser) WaitDOMQuiet

func (b *Browser) WaitDOMQuiet(quiet, max time.Duration, minText int) (DOMQuiet, error)

WaitDOMQuiet waits until the page stops changing its own DOM: quiet is the stretch of calm that ends the wait, max the longest it may take, and minText how much readable text a quiet page must already have for the wait to count as finished.

func (*Browser) WaitQuiet

func (b *Browser) WaitQuiet(interval, max time.Duration)

WaitQuiet returns once the layout fingerprint has stayed the same for interval, or after max. Use it after a navigation so a dump reflects the page after its late scripts (banners, lazy content) have run.

func (*Browser) WaitSettled

func (b *Browser) WaitSettled(max time.Duration)

WaitSettled blocks until the page fires a load or frameStoppedLoading event, or max elapses. Call it after an action that may trigger a load.

func (*Browser) WakeUp

func (b *Browser) WakeUp(pause time.Duration, maxSteps int, max time.Duration) (Wake, error)

WakeUp scrolls through the whole page once and comes back, so lazy images load and scroll-revealed blocks appear before the first capture.

func (*Browser) WakeUpTo

func (b *Browser) WakeUpTo(pause time.Duration, maxSteps int, max time.Duration, reach float64) (Wake, error)

WakeUpTo wakes the page down to reach CSS pixels below the top, or the whole page when reach is 0.

func (*Browser) WalkerRuns

func (b *Browser) WalkerRuns() ([]frame.TextRun, error)

WalkerRuns measures the page text in the page, character by character.

func (*Browser) Wheel

func (b *Browser) Wheel(col, row, deltaRows int) error

Wheel scrolls whatever is under a cell by deltaRows rows, positive down, like a mouse wheel.

func (*Browser) Zoom

func (b *Browser) Zoom() float64

Zoom returns the page zoom factor.

type CaptureStats

type CaptureStats struct {
	Screenshot time.Duration // last screenshot, decode included
	Walker     time.Duration // last text pass
	Attempts   int           // 1 unless the layout moved in between
	Source     string        // where the text came from: "walk", "snap" or "ui"
	Prep       time.Duration // media preparation, only for the ui renderer
	Snapshot   time.Duration // the DOM snapshot itself
	Crops      time.Duration // the media crops
	NCrops     int
}

CaptureStats reports how a Capture went.

type DOMQuiet

type DOMQuiet struct {
	Why  string `json:"why"`  // "quiet", "timeout" or "no observer"
	Ms   int    `json:"ms"`   // how long the wait took, in the page's clock
	Text int    `json:"text"` // characters of text the document ended up with
}

DOMQuiet reports how waiting for the page to settle went.

type MediaPrep

type MediaPrep struct {
	Images  int `json:"images"`
	Waited  int `json:"waited"`
	Videos  int `json:"videos"`
	Playing int `json:"playing"`
}

MediaPrep reports what the media preparation pass found.

type Options

type Options struct {
	ChromePath string // empty: chromedp autodetects the binary
	// ProfileDir is the directory Chrome keeps its profile in, so
	// cookies, consents and logins outlive the session. Empty means a
	// throwaway profile.
	ProfileDir string
	// Audio lets pages play sound through the system output, and lets a
	// video start with its sound without a click. Off, every video plays
	// muted and Chrome makes no sound at all.
	Audio bool
	// Opacity says how an element at opacity 0 is read. "pending", the
	// default, treats one that is animating its opacity as visible, since
	// it is about to appear. "strict" hides it regardless. "ignore" reads
	// every such element as visible: the text is taken from the DOM even
	// where the page paints nothing, for sites whose reveal animations
	// never fire in a headless browser. Display, visibility and the clip
	// of the ancestors are respected in every mode.
	Opacity    string
	Grid       grid.Grid     // initial viewport
	Headless   bool          // false opens a visible window, for debugging
	NavTimeout time.Duration // wait for the load event; 10s when zero
	// Zoom scales the page: the CSS viewport is the grid's pixel size divided
	// by Zoom and the page is rendered at deviceScaleFactor Zoom, so
	// graphics grow while every character still fills exactly one cell.
	// 1 when zero.
	Zoom float64
	// Renderer picks how the page is read: "shot" takes a screenshot and
	// measures the text in the page, "snap" takes a screenshot and reads
	// the text from DOMSnapshot, "ui" draws the interface from DOMSnapshot
	// with no screenshot at all, and "auto" (the default) picks the text
	// source by frame height. Empty means "auto".
	Renderer string
	// UIMedia photographs each media element and renders it inside its
	// frame instead of drawing a placeholder. Only the "ui" renderer
	// uses it.
	UIMedia bool
	// Video is how a <video> is drawn: "off" leaves a placeholder,
	// "poster" renders it once and never again, "live" refreshes it at
	// VideoFPS without recapturing the page. Empty means "poster".
	Video string
	// VideoFPS caps how often a live video is refreshed; 0 means 2.
	VideoFPS float64
	// ScreenRows is one screenful of the frame, in rows; "auto" switches
	// to the snapshot once the frame is four of them or taller. 0 means
	// the whole frame is one screen.
	ScreenRows int
	// ShotFormat is the screenshot encoding: "png", "jpeg", or "auto"
	// (default): png up to jpegAbovePixels device pixels, jpeg beyond, where
	// png encoding and decoding start to dominate the frame time. After
	// averaging 128 pixels per cell the two are indistinguishable.
	ShotFormat string
}

Options configure a Browser.

type Page

type Page struct {
	Img   image.Image
	Runs  []frame.TextRun
	UI    []frame.UIBox
	State PageState
	Stats CaptureStats
}

Page is one capture of the page: the pixels (nil for the interface renderer), the text, the interface layer, and the page state.

type PageState

type PageState struct {
	// Fingerprint summarises the layout: scroll position, document height
	// and element count. Two captures taken while it is unchanged share
	// the same geometry.
	Fingerprint string  `json:"fp"`
	URL         string  `json:"url"`
	Title       string  `json:"title"`
	Focus       string  `json:"focus"`      // "input" while a text field or editable element has focus
	Fullscreen  bool    `json:"fullscreen"` // an element, usually a video player, is fullscreen
	BgLuma      float64 `json:"bgLuma"`     // luminance of the page background, 0 black to 1 white
	// Videos are the boxes of the videos on screen, in CSS pixels of the
	// viewport, for renderers that do not take a layout snapshot.
	Videos       []VideoRect `json:"videos"`
	CaretLeft    float64     `json:"caretLeft"` // content box of the focused field, CSS pixels
	CaretTop     float64     `json:"caretTop"`
	CaretHeight  float64     `json:"caretHeight"`
	CaretIndex   int         `json:"caretIndex"` // characters before the caret
	ScrollY      float64     `json:"scrollY"`
	ScrollHeight float64     `json:"scrollHeight"`
	ViewportH    float64     `json:"viewportH"`
}

PageState is what the UI needs to know about the page besides its pixels and text: where it is, whether a text field has focus, and how far it is scrolled.

type ScreencastFrame

type ScreencastFrame struct {
	Img       image.Image
	ScrollX   float64   // CSS pixels
	ScrollY   float64   // CSS pixels
	Timestamp time.Time // frame swap time, Chrome's wall clock
	// contains filtered or unexported fields
}

ScreencastFrame is one frame pushed by Chrome: the page repainted. Img is the decoded frame; it matches the grid's pixel size unless Chrome scaled it down, in which case the receiver should fall back to Capture. Ack must be called once the frame has been consumed: Chrome keeps at most a couple of frames in flight and waits for acknowledgements, which is what throttles a page that repaints continuously to the receiver's pace.

func (*ScreencastFrame) Ack

func (f *ScreencastFrame) Ack()

Ack tells Chrome the frame was consumed, so the next one may be sent. Frames this one replaced are acknowledged at the same time: holding their acknowledgement until now is what keeps Chrome from encoding frames faster than they are consumed.

func (*ScreencastFrame) Supersede

func (f *ScreencastFrame) Supersede(old *ScreencastFrame)

Supersede makes f stand in for an older frame that will not be processed: the older frame is acknowledged when f is.

type VideoFrame

type VideoFrame struct {
	X     int      `json:"x"`
	Y     int      `json:"y"`
	Cols  int      `json:"cols"`
	Rows  int      `json:"rows"`
	N     int      `json:"n"`
	Lines []string `json:"lines"`
	// Tainted marks a video whose pixels the page may not read, because
	// it comes from another origin without CORS. There are no lines: Go
	// photographs the box itself instead.
	Tainted bool `json:"tainted"`
}

VideoFrame is one video frame already turned into characters by the page: the rows of text and where they go, in cells.

type VideoOptions

type VideoOptions struct {
	Ramp   string
	Invert bool
	Paper  float64
	FPS    float64 // 0: as fast as the video decodes
	Once   bool    // stop after the first frame (the poster mode)
}

VideoOptions is what the page needs to render a video the same way the rest of the frame is rendered.

type VideoRect

type VideoRect struct {
	L float64 `json:"l"`
	T float64 `json:"t"`
	W float64 `json:"w"`
	H float64 `json:"h"`
}

VideoRect is a video's box in CSS pixels, relative to the viewport.

type Wake

type Wake struct {
	Steps  int `json:"steps"`  // screens scrolled through
	Height int `json:"height"` // document height at the end, CSS pixels
	Ms     int `json:"ms"`
}

Wake reports how the wake-up scroll went.

Jump to

Keyboard shortcuts

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