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 ¶
- type Browser
- func (b *Browser) Back() error
- func (b *Browser) Blur() error
- func (b *Browser) Capture(withText bool) (Page, error)
- func (b *Browser) Click(col, row int) error
- func (b *Browser) Close() error
- func (b *Browser) ConsentReloaded() bool
- func (b *Browser) Context() context.Context
- func (b *Browser) CropCells(x, y, w, h int) (image.Image, error)
- func (b *Browser) DismissConsent(prefer string, max time.Duration) ([]string, error)
- func (b *Browser) FollowReload(seq int64, max time.Duration) bool
- func (b *Browser) Forward() error
- func (b *Browser) Grid() grid.Grid
- func (b *Browser) InsertText(s string) error
- func (b *Browser) Key(key string) error
- func (b *Browser) NavSeq() int64
- func (b *Browser) Navigate(url string) error
- func (b *Browser) PrepareMedia(timeout time.Duration) (MediaPrep, error)
- func (b *Browser) ProfileNote() string
- func (b *Browser) Reload() error
- func (b *Browser) Resize(g grid.Grid) error
- func (b *Browser) Screenshot() (image.Image, error)
- func (b *Browser) ScrollBy(deltaRows int) error
- func (b *Browser) ScrollHeight() (int, error)
- func (b *Browser) ScrollTo(bottom bool) error
- func (b *Browser) ScrollToRow(row int) error
- func (b *Browser) SetScreenRows(n int)
- func (b *Browser) SnapshotRuns() ([]frame.TextRun, error)
- func (b *Browser) SnapshotUI() ([]frame.TextRun, []frame.UIBox, error)
- func (b *Browser) StartScreencast() (<-chan *ScreencastFrame, error)
- func (b *Browser) StartVideo(opts VideoOptions) error
- func (b *Browser) State() (PageState, error)
- func (b *Browser) StopScreencast() error
- func (b *Browser) TextRuns() ([]frame.TextRun, error)
- func (b *Browser) Title() (string, error)
- func (b *Browser) URL() (string, error)
- func (b *Browser) VideoFrames() <-chan VideoFrame
- func (b *Browser) VideoInterval() time.Duration
- func (b *Browser) VideoMode() string
- func (b *Browser) VideoStatus() string
- func (b *Browser) WaitDOMQuiet(quiet, max time.Duration, minText int) (DOMQuiet, error)
- func (b *Browser) WaitQuiet(interval, max time.Duration)
- func (b *Browser) WaitSettled(max time.Duration)
- func (b *Browser) WakeUp(pause time.Duration, maxSteps int, max time.Duration) (Wake, error)
- func (b *Browser) WakeUpTo(pause time.Duration, maxSteps int, max time.Duration, reach float64) (Wake, error)
- func (b *Browser) WalkerRuns() ([]frame.TextRun, error)
- func (b *Browser) Wheel(col, row, deltaRows int) error
- func (b *Browser) Zoom() float64
- type CaptureStats
- type DOMQuiet
- type MediaPrep
- type Options
- type Page
- type PageState
- type ScreencastFrame
- type VideoFrame
- type VideoOptions
- type VideoRect
- type Wake
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 ¶
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) Capture ¶
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 ¶
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) ConsentReloaded ¶
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) CropCells ¶
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 ¶
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 ¶
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) InsertText ¶
InsertText types text into the focused element, as an IME would.
func (*Browser) Key ¶
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) PrepareMedia ¶
PrepareMedia loads lazy images and starts videos, waiting at most timeout for the images to arrive.
func (*Browser) ProfileNote ¶
ProfileNote is non-empty when the wanted profile could not be used.
func (*Browser) Resize ¶
Resize changes the viewport to match a new grid. A running screencast is restarted at the new size.
func (*Browser) Screenshot ¶
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) ScrollHeight ¶
ScrollHeight returns the full document height in CSS pixels.
func (*Browser) ScrollToRow ¶
ScrollToRow scrolls the window so that the given grid row is at the top of the viewport.
func (*Browser) SetScreenRows ¶
SetScreenRows tells the browser how tall one screenful is, which is what the "auto" renderer weighs against the frame height.
func (*Browser) SnapshotRuns ¶
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 ¶
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) StopScreencast ¶
StopScreencast stops the frame stream.
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 ¶
VideoInterval is the shortest gap between refreshes of a live video.
func (*Browser) VideoStatus ¶
VideoStatus reports what the last injection did, for the log.
func (*Browser) WaitDOMQuiet ¶
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 ¶
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 ¶
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 ¶
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 ¶
WalkerRuns measures the page text in the page, character by character.
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
// 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.