browser

package
v2.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 30 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 real Chromium on a target over the Chrome DevTools Protocol, for the session Browser pane, Design Mode and the agent browser tools (docs/browser.md).

The browser runs where the session's agent runs, so it sees that machine's localhost exactly as the agent does. Its DevTools port is bound to the target's loopback and reached through the same executor dialer that live port forwards use; nothing new listens on the target's network.

Index

Constants

View Source
const PickerPath = "/__lectern/design.js"

PickerPath is where a view serves the picker while Design Mode is on.

View Source
const TicketParam = "__lectern_ticket"

TicketParam carries a single-use ticket in the first URL a view is opened at.

View Source
const ViewCookiePrefix = "lectern_view_"

ViewCookiePrefix names the cookie each view sets; it is also stripped from what reaches the dev server, with Lectern's own cookies.

Variables

View Source
var ErrClosed = errors.New("the browser has closed")

ErrClosed means the browser connection is gone.

View Source
var ErrNoBrowser = errors.New("no Chromium or Chrome is installed on this machine " +
	"(install chromium, or run `npx playwright install chromium`)")

ErrNoBrowser means the machine has no Chromium-family browser to start.

View Source
var ErrNotFound = errors.New("no element matches")

ErrNotFound means no element matched.

View Source
var ErrPageGone = errors.New("the page closed")

ErrPageGone means the page a call was sent to closed before answering; a click that closes its own window ends this way.

View Source
var ProfileName = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)

ProfileName is what a persistent profile may be called.

Functions

func CheckURL

func CheckURL(raw string) (string, error)

CheckURL accepts only web addresses: the browser is for pages, not for reading the machine's files.

func Find

func Find(ctx context.Context, run Runner) (string, string, error)

Find names the browser Launch would start on a machine, and its version, or returns ErrNoBrowser.

func InjectPicker

func InjectPicker(doc []byte) []byte

InjectPicker puts the picker's script tag at the top of a document.

func Injectable

func Injectable(design bool, req *http.Request, resp *http.Response) bool

Injectable is the whole allowlist for Design Mode injection: Design Mode on, a same-site document request, and a successful, uncompressed, inline HTML response. Everything else passes through byte for byte.

func KeepAlive

func KeepAlive(ctx context.Context, run Runner, dirs ...string) error

KeepAlive tells other servers on the machine this browser is still in use; Launch reaps one whose owner stopped doing this.

func PickerScript

func PickerScript(mode, parentOrigin string) string

PickerScript is Design Mode's element picker. mode is "cdp" (it reports through a DevTools binding) or "frame" (it reports to parentOrigin with postMessage, from inside the Browser pane's iframe).

func Stop

func Stop(ctx context.Context, run Runner, dir string) error

Stop ends a browser and removes its profile.

func StripLecternCookies

func StripLecternCookies(h http.Header)

StripLecternCookies removes Lectern's own credentials and every view cookie from a Cookie header, so a dev server never sees them.

func ValidOrigin

func ValidOrigin(s string) bool

ValidOrigin reports whether s is a bare http(s) origin.

Types

type Browser

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

Browser is one page of a browser, driven over DevTools. The first page owns the connection; NewPage opens more on it.

func Open

func Open(ctx context.Context, dial Dial, proc *Process, vp Viewport) (*Browser, error)

Open connects to a started browser and opens its page.

func (*Browser) Click

func (b *Browser) Click(ctx context.Context, t Target) (State, error)

Click clicks an element's middle, the way a person would.

func (*Browser) ClickAt

func (b *Browser) ClickAt(ctx context.Context, x, y float64) error

ClickAt clicks a point in the viewport.

func (*Browser) Close

func (b *Browser) Close()

Close ends the page, and the connection if this page owns it.

func (*Browser) Console

func (b *Browser) Console() []LogEntry

Console returns the recent console messages, oldest first.

func (*Browser) DescribeSelector

func (b *Browser) DescribeSelector(ctx context.Context, selector string) (json.RawMessage, error)

DescribeSelector runs the picker's own description of the element at selector: the same payload a click in Design Mode produces. It is how a fresh render of a page yields the element an operator picked elsewhere.

func (*Browser) Dispatch

func (b *Browser) Dispatch(ctx context.Context, in Input) error

Dispatch replays one pane event into the page.

func (*Browser) Done

func (b *Browser) Done() <-chan struct{}

Done is closed when the browser goes away.

func (*Browser) Evaluate

func (b *Browser) Evaluate(ctx context.Context, expression string) (any, error)

Evaluate runs a read-only expression: DevTools refuses anything with a side effect (a write to the DOM, a network call, an assignment to a global), so an agent can inspect the page but not change it this way.

func (*Browser) Fill

func (b *Browser) Fill(ctx context.Context, t Target, text string) (State, error)

Fill replaces an input's value with text, as typing would, so the page's own input handlers run. A select element picks the option by value or label.

func (*Browser) Find

func (b *Browser) Find(ctx context.Context, text string, backwards bool) (FindResult, error)

Find selects the next (or previous) match of text in the page and scrolls to it, as a browser's own find does, and counts the matches.

func (*Browser) HidePicker

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

HidePicker removes the picker's highlight before a screenshot.

func (*Browser) History

func (b *Browser) History(ctx context.Context, delta int) (State, error)

History moves back (-1) or forward (+1).

func (*Browser) Navigate

func (b *Browser) Navigate(ctx context.Context, raw string) (State, error)

Navigate loads an address and waits for it to finish loading, up to 15s.

func (*Browser) Network

func (b *Browser) Network() []NetEntry

Network returns the recent requests, oldest first.

func (*Browser) NewPage

func (b *Browser) NewPage(ctx context.Context, vp Viewport) (*Browser, error)

NewPage opens a separate page in the same browser, e.g. for a fresh render that must not disturb the page someone is watching.

func (*Browser) Press

func (b *Browser) Press(ctx context.Context, combo string) error

Press sends one key, optionally with modifiers.

func (*Browser) Reload

func (b *Browser) Reload(ctx context.Context) (State, error)

Reload reloads the page.

func (*Browser) Resize

func (b *Browser) Resize(ctx context.Context, vp Viewport) (State, error)

Resize changes the viewport, e.g. to a phone's size.

func (*Browser) Screenshot

func (b *Browser) Screenshot(ctx context.Context, clip *Clip) ([]byte, error)

Screenshot captures the viewport, or clip when given, as PNG.

func (*Browser) SetDesign

func (b *Browser) SetDesign(ctx context.Context, on bool) error

SetDesign turns the element picker on or off in the live page. While on it is also installed into every page the browser loads.

func (*Browser) Snapshot

func (b *Browser) Snapshot(ctx context.Context) (Snapshot, error)

Snapshot reads the page's accessibility tree. Refs from any earlier snapshot stop working: a ref names an element as it was when read.

func (*Browser) State

func (b *Browser) State() State

State reports the current page.

func (*Browser) Sync

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

Sync reads the page's address and title, for a page attached after it had already started loading.

func (*Browser) Watch

func (b *Browser) Watch(ctx context.Context) (<-chan Frame, <-chan Update, func())

Watch subscribes to screencast frames and updates until the returned stop function runs. The first watcher starts the screencast; the last one out stops it, so an unwatched browser costs no encoding.

type Clip

type Clip struct {
	X      float64 `json:"x"`
	Y      float64 `json:"y"`
	Width  float64 `json:"width"`
	Height float64 `json:"height"`
}

Clip is a rectangle in document CSS pixels.

type Conn

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

Conn is one DevTools WebSocket to a browser. Commands are correlated by id; events go to the handler of the page session they belong to, which must not block for long.

func (*Conn) Call

func (c *Conn) Call(ctx context.Context, sessionID, method string, params any, result any) error

Call sends one command and waits for its result. sessionID is the flattened page session, or "" for the browser itself.

func (*Conn) Close

func (c *Conn) Close()

Close ends the connection. The browser process is stopped separately.

func (*Conn) Done

func (c *Conn) Done() <-chan struct{}

Done is closed when the connection ends.

type CookieResult

type CookieResult struct {
	Imported int            `json:"imported"`
	Skipped  map[string]int `json:"skipped"`
	Sites    int            `json:"sites"`
}

CookieResult is what an import reports: counts only, never a cookie.

func ImportCookies

func ImportCookies(ctx context.Context, run Runner, proc *Process, kind, source string, domains []string) (CookieResult, error)

ImportCookies loads cookies into a running browser from its own machine: kind "file" reads (and then deletes) a cookies file at source, in Netscape cookies.txt or JSON form; kind "chrome" reads a local Chrome, Chromium, Brave or Edge profile directory ("auto" finds one). domains, when not empty, limits the import to those sites. The work happens in a script on that machine, which talks to the browser over its loopback DevTools port, so cookie values never pass through Lectern.

func ImportCookiesWith added in v2.7.0

func ImportCookiesWith(ctx context.Context, run Runner, lectern string, proc *Process, kind, source string, domains []string) (CookieResult, error)

ImportCookiesWith is ImportCookies on a machine whose lectern binary is at lectern ("" for none): a cookies file is then read by `lectern helper browser-cookies`. A Chrome profile always needs the Python script, which reads the profile's SQLite database.

type Dial

type Dial func(ctx context.Context, addr string) (net.Conn, error)

Dial opens a TCP connection to addr as the machine running the browser sees it.

type Download

type Download struct {
	GUID     string  `json:"-"`
	URL      string  `json:"url"`
	Name     string  `json:"name"`
	Path     string  `json:"path"`
	State    string  `json:"state"` // inProgress | completed | canceled
	Received int64   `json:"received"`
	Total    int64   `json:"total"`
	Time     float64 `json:"time"`
}

Download is one file a page downloaded.

type Event

type Event struct {
	Method    string
	Params    json.RawMessage
	SessionID string
}

Event is one DevTools event, with the flattened session it belongs to.

type FindResult

type FindResult struct {
	Matches int  `json:"matches"`
	Index   int  `json:"index"` // 1-based; 0 when nothing matches
	Found   bool `json:"found"`
}

FindResult is where a find-in-page search stands.

type Frame

type Frame struct {
	JPEG      []byte
	Width     int
	Height    int
	PageScale float64
}

Frame is one screencast image. PageScale is the page's zoom when a phone viewport shows a page laid out wider (one with no viewport meta tag): input coordinates are layout pixels, the picture is zoomed by this much.

type Input

type Input struct {
	Type      string  `json:"type"` // mousemove|mousedown|mouseup|wheel|keydown|keyup|text
	X         float64 `json:"x"`
	Y         float64 `json:"y"`
	Button    string  `json:"button"`
	Clicks    int     `json:"clicks"`
	DeltaX    float64 `json:"dx"`
	DeltaY    float64 `json:"dy"`
	Key       string  `json:"key"`
	Code      string  `json:"code"`
	KeyCode   int     `json:"key_code"`
	Text      string  `json:"text"`
	Modifiers int     `json:"modifiers"`
}

Input is one mouse, key or text event from the Browser pane, in viewport CSS pixels.

type LaunchOptions

type LaunchOptions struct {
	Width, Height int
	// Profile names a persistent profile under ~/.lectern/browser-profiles on
	// the browser's machine; cookies and storage in it survive the browser.
	// "" is a throwaway profile removed with the browser.
	Profile string
	// ProxyPort, when set, sends every request — loopback included — through
	// an HTTP proxy on 127.0.0.1 of the machine running the browser. It is how
	// a browser on the control plane still sees a target's localhost.
	ProxyPort int
}

LaunchOptions shape one browser.

type LogEntry

type LogEntry struct {
	Time  float64 `json:"time"`
	Level string  `json:"level"`
	Text  string  `json:"text"`
	URL   string  `json:"url,omitempty"`
}

LogEntry is one console message or uncaught exception.

type LoopbackProxy

type LoopbackProxy struct {
	Port int
	// contains filtered or unexported fields
}

LoopbackProxy lets a browser on the control plane stand in for one on a target that has none: the browser's requests for localhost go to the target's loopback, and everything else goes out from here. It listens on the control plane's own loopback, for as long as that browser lives, and on Linux accepts only connections from processes of this same user.

func StartLoopbackProxy

func StartLoopbackProxy(dial Dial) (*LoopbackProxy, error)

StartLoopbackProxy starts the proxy. dial reaches the target's loopback.

func (*LoopbackProxy) Close

func (p *LoopbackProxy) Close()

Close stops the proxy.

type NetEntry

type NetEntry struct {
	Time     float64 `json:"time"`
	ID       string  `json:"-"`
	Method   string  `json:"method"`
	URL      string  `json:"url"`
	Type     string  `json:"type,omitempty"`
	Status   int     `json:"status,omitempty"`
	MimeType string  `json:"mime_type,omitempty"`
	Failed   string  `json:"failed,omitempty"`
}

NetEntry is one request the page made.

type Process

type Process struct {
	Dir    string // private state: pid, log, profile
	Port   int    // DevTools, on that machine's loopback
	Path   string // the browser-level DevTools WebSocket path
	Binary string
}

Process is one headless browser started by Launch.

func Launch

func Launch(ctx context.Context, run Runner, owner string, opts LaunchOptions) (*Process, error)

Launch starts a headless browser. owner identifies this server process, so a later server can tell its own browsers from ones an earlier one abandoned.

type Runner

type Runner func(ctx context.Context, script string) (string, error)

Runner executes a shell script on one machine and returns its stdout.

type Snapshot

type Snapshot struct {
	URL   string `json:"url"`
	Title string `json:"title"`
	Tree  string `json:"tree"`
	Refs  int    `json:"refs"`
}

Snapshot is the page as an agent reads it: an accessibility outline in which every element it can act on carries a ref for click and fill.

type State

type State struct {
	URL      string   `json:"url"`
	Title    string   `json:"title"`
	Viewport Viewport `json:"viewport"`
	Design   bool     `json:"design"`
}

State is the page as it stands.

type TabInfo

type TabInfo struct {
	ID     int    `json:"id"`
	URL    string `json:"url"`
	Title  string `json:"title"`
	Active bool   `json:"active"`
}

TabInfo describes one tab.

type Tabs

type Tabs struct {

	// OnDownload runs when a download finishes and returns where the file
	// ended up. The browser saves each one under its id, so two files with
	// one name never overwrite each other; this gives it its name back.
	OnDownload func(d Download) string
	// contains filtered or unexported fields
}

Tabs is one browser with its pages: the tab strip the Browser pane shows and the agent's tools address by id. A page a tab opens (a target=_blank link, window.open) becomes a tab of its own. Downloads from any tab land in one directory on the browser's machine.

func OpenTabs

func OpenTabs(ctx context.Context, dial Dial, proc *Process, vp Viewport, downloadDir string) (*Tabs, error)

OpenTabs connects to a started browser and opens its first tab. Downloads go to downloadDir, which must be an absolute path on the browser's machine; "" leaves them refused.

func (*Tabs) Active

func (t *Tabs) Active() int

Active is the active tab's id.

func (*Tabs) Changes

func (t *Tabs) Changes() (<-chan struct{}, func())

Changes signals whenever tabs open, close or change which is active, or a download moves.

func (*Tabs) Close

func (t *Tabs) Close()

Close ends the connection; the process is stopped separately.

func (*Tabs) CloseTab

func (t *Tabs) CloseTab(ctx context.Context, id int) error

CloseTab closes one tab. Closing the last one leaves a blank tab, so there is always a page to show.

func (*Tabs) Done

func (t *Tabs) Done() <-chan struct{}

Done is closed when the browser goes away.

func (*Tabs) Downloads

func (t *Tabs) Downloads() []Download

Downloads lists this browser's downloads, newest last.

func (*Tabs) Get

func (t *Tabs) Get(id int) (*Browser, int, error)

Get returns tab id, or the active tab for 0.

func (*Tabs) List

func (t *Tabs) List() []TabInfo

List reports the open tabs in the order they were opened.

func (*Tabs) New

func (t *Tabs) New(ctx context.Context, address string) (int, *Browser, error)

New opens a tab, at address when given, and makes it the active one.

func (*Tabs) Quit

func (t *Tabs) Quit(ctx context.Context)

Quit asks the browser to exit on its own, which is when it writes a persistent profile's cookies and storage to disk, and waits for it. A browser only killed loses whatever it had not flushed yet.

func (*Tabs) Resize

func (t *Tabs) Resize(ctx context.Context, vp Viewport) error

Resize sets the viewport of every tab, and of tabs opened later.

func (*Tabs) Select

func (t *Tabs) Select(id int) error

Select makes a tab the active one: the one the pane shows and tools use by default.

type Target

type Target struct {
	Ref      int    `json:"ref"`
	Selector string `json:"selector"`
}

Target names an element: a ref from the last snapshot, or a CSS selector.

type Update

type Update struct {
	Kind   string          `json:"kind"` // state | design
	URL    string          `json:"url,omitempty"`
	Title  string          `json:"title,omitempty"`
	Design json.RawMessage `json:"design,omitempty"`
}

Update is what a watcher hears besides frames: page state changes and Design Mode selections.

type View

type View struct {
	ID           string
	Port         int // on the target's loopback
	ListenPort   int
	ParentOrigin string
	Created      float64

	TLS bool // the listener also speaks TLS (it sniffs each connection)
	// contains filtered or unexported fields
}

View serves one port of a target's localhost on an origin of its own, so the Browser pane can frame a dev server exactly as it runs: absolute asset paths, redirects and hot-reload websockets all work, which a path-prefix proxy breaks.

A view is not an open door like a raw port forward. Every request needs a cookie the view sets only after it is opened with a single-use ticket, and tickets are minted by an authenticated Lectern API call. Lectern's own cookies are removed before anything reaches the dev server.

Design Mode is the one place the proxy changes a response: while it is on, HTML documents from this view get one same-origin script tag for the picker. Nothing else is ever injected, and nothing from any other origin passes through here at all.

func OpenView

func OpenView(dial Dial, port int, bindHost string, lo, hi int, tlsConf *tls.Config, parentOrigin string) (*View, error)

OpenView listens on the first free port in [lo, hi] on bindHost. tlsConf, when set, lets the same port answer https as well, so a view can be framed by a Lectern page served over TLS.

func (*View) Close

func (v *View) Close()

Close stops the view.

func (*View) Design

func (v *View) Design() bool

Design reports whether Design Mode is on for this view.

func (*View) ServeHTTP

func (v *View) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*View) SetDesign

func (v *View) SetDesign(on bool)

SetDesign turns picker injection on or off for this view's documents.

func (*View) Ticket

func (v *View) Ticket() string

Ticket mints a single-use ticket, good for two minutes, that opens the view in one browser.

type Viewport

type Viewport struct {
	Width  int     `json:"width"`
	Height int     `json:"height"`
	Mobile bool    `json:"mobile"`
	Scale  float64 `json:"scale"`
}

Viewport is the page size the browser renders at, in CSS pixels.

Jump to

Keyboard shortcuts

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