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
- Variables
- func CheckURL(raw string) (string, error)
- func Find(ctx context.Context, run Runner) (string, string, error)
- func InjectPicker(doc []byte) []byte
- func Injectable(design bool, req *http.Request, resp *http.Response) bool
- func KeepAlive(ctx context.Context, run Runner, dirs ...string) error
- func PickerScript(mode, parentOrigin string) string
- func Stop(ctx context.Context, run Runner, dir string) error
- func StripLecternCookies(h http.Header)
- func ValidOrigin(s string) bool
- type Browser
- func (b *Browser) Click(ctx context.Context, t Target) (State, error)
- func (b *Browser) ClickAt(ctx context.Context, x, y float64) error
- func (b *Browser) Close()
- func (b *Browser) Console() []LogEntry
- func (b *Browser) DescribeSelector(ctx context.Context, selector string) (json.RawMessage, error)
- func (b *Browser) Dispatch(ctx context.Context, in Input) error
- func (b *Browser) Done() <-chan struct{}
- func (b *Browser) Evaluate(ctx context.Context, expression string) (any, error)
- func (b *Browser) Fill(ctx context.Context, t Target, text string) (State, error)
- func (b *Browser) Find(ctx context.Context, text string, backwards bool) (FindResult, error)
- func (b *Browser) HidePicker(ctx context.Context)
- func (b *Browser) History(ctx context.Context, delta int) (State, error)
- func (b *Browser) Navigate(ctx context.Context, raw string) (State, error)
- func (b *Browser) Network() []NetEntry
- func (b *Browser) NewPage(ctx context.Context, vp Viewport) (*Browser, error)
- func (b *Browser) Press(ctx context.Context, combo string) error
- func (b *Browser) Reload(ctx context.Context) (State, error)
- func (b *Browser) Resize(ctx context.Context, vp Viewport) (State, error)
- func (b *Browser) Screenshot(ctx context.Context, clip *Clip) ([]byte, error)
- func (b *Browser) SetDesign(ctx context.Context, on bool) error
- func (b *Browser) Snapshot(ctx context.Context) (Snapshot, error)
- func (b *Browser) State() State
- func (b *Browser) Sync(ctx context.Context)
- func (b *Browser) Watch(ctx context.Context) (<-chan Frame, <-chan Update, func())
- type Clip
- type Conn
- type CookieResult
- type Dial
- type Download
- type Event
- type FindResult
- type Frame
- type Input
- type LaunchOptions
- type LogEntry
- type LoopbackProxy
- type NetEntry
- type Process
- type Runner
- type Snapshot
- type State
- type TabInfo
- type Tabs
- func (t *Tabs) Active() int
- func (t *Tabs) Changes() (<-chan struct{}, func())
- func (t *Tabs) Close()
- func (t *Tabs) CloseTab(ctx context.Context, id int) error
- func (t *Tabs) Done() <-chan struct{}
- func (t *Tabs) Downloads() []Download
- func (t *Tabs) Get(id int) (*Browser, int, error)
- func (t *Tabs) List() []TabInfo
- func (t *Tabs) New(ctx context.Context, address string) (int, *Browser, error)
- func (t *Tabs) Quit(ctx context.Context)
- func (t *Tabs) Resize(ctx context.Context, vp Viewport) error
- func (t *Tabs) Select(id int) error
- type Target
- type Update
- type View
- type Viewport
Constants ¶
const PickerPath = "/__lectern/design.js"
PickerPath is where a view serves the picker while Design Mode is on.
const TicketParam = "__lectern_ticket"
TicketParam carries a single-use ticket in the first URL a view is opened at.
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 ¶
var ErrClosed = errors.New("the browser has closed")
ErrClosed means the browser connection is gone.
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.
var ErrNotFound = errors.New("no element matches")
ErrNotFound means no element matched.
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.
var ProfileName = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
ProfileName is what a persistent profile may be called.
Functions ¶
func CheckURL ¶
CheckURL accepts only web addresses: the browser is for pages, not for reading the machine's files.
func Find ¶
Find names the browser Launch would start on a machine, and its version, or returns ErrNoBrowser.
func InjectPicker ¶
InjectPicker puts the picker's script tag at the top of a document.
func Injectable ¶
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 ¶
KeepAlive tells other servers on the machine this browser is still in use; Launch reaps one whose owner stopped doing this.
func PickerScript ¶
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 StripLecternCookies ¶
StripLecternCookies removes Lectern's own credentials and every view cookie from a Cookie header, so a dev server never sees them.
func ValidOrigin ¶
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 (*Browser) Close ¶
func (b *Browser) Close()
Close ends the page, and the connection if this page owns it.
func (*Browser) DescribeSelector ¶
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) Done ¶
func (b *Browser) Done() <-chan struct{}
Done is closed when the browser goes away.
func (*Browser) Evaluate ¶
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 ¶
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 ¶
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 ¶
HidePicker removes the picker's highlight before a screenshot.
func (*Browser) NewPage ¶
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) Screenshot ¶
Screenshot captures the viewport, or clip when given, as PNG.
func (*Browser) SetDesign ¶
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 ¶
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) Sync ¶
Sync reads the page's address and title, for a page attached after it had already started loading.
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 ¶
Call sends one command and waits for its result. sessionID is the flattened page session, or "" for the browser itself.
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 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 ¶
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.
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.
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) 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 ¶
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) Quit ¶
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.
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.