Documentation
¶
Overview ¶
Package browser drives a real Chromium over the DevTools protocol. It speaks CDP directly rather than shelling out to a driver, so the only dependency is a Chrome binary that is already on the machine.
Index ¶
- func FindExecutable(override string) (string, error)
- type Cookie
- type NetworkRequest
- type NetworkResponse
- type Options
- type Session
- func (s *Session) Back(ctx context.Context) error
- func (s *Session) Click(ctx context.Context, ref string) (string, error)
- func (s *Session) ClickSelector(ctx context.Context, sel string) (string, error)
- func (s *Session) ClickXY(ctx context.Context, x, y float64) error
- func (s *Session) Console() []string
- func (s *Session) Cookies(ctx context.Context, urls ...string) ([]Cookie, error)
- func (s *Session) DrainNetwork(ctx context.Context) []NetworkRequest
- func (s *Session) Eval(ctx context.Context, expression string) (json.RawMessage, error)
- func (s *Session) EvalFunc(ctx context.Context, body string, args ...any) (json.RawMessage, error)
- func (s *Session) EvalString(ctx context.Context, expression string) (string, error)
- func (s *Session) FillSelector(ctx context.Context, sel, value string) (string, error)
- func (s *Session) InsertText(ctx context.Context, text string) error
- func (s *Session) LastUsed() time.Time
- func (s *Session) Navigate(ctx context.Context, url string) error
- func (s *Session) PressKey(ctx context.Context, key string) error
- func (s *Session) PressSelector(ctx context.Context, sel, key string, timeout time.Duration) error
- func (s *Session) Requests() []string
- func (s *Session) ResponseBody(ctx context.Context, requestID string) (body string, mimeType string, err error)
- func (s *Session) Screenshot(ctx context.Context, fullPage bool) ([]byte, error)
- func (s *Session) Scroll(ctx context.Context, direction string, amount int) (string, error)
- func (s *Session) Select(ctx context.Context, ref, value string) (string, error)
- func (s *Session) SetCookies(ctx context.Context, cookies []Cookie) error
- func (s *Session) Snapshot(ctx context.Context, max int) (string, error)
- func (s *Session) Start(ctx context.Context) error
- func (s *Session) Started() bool
- func (s *Session) Stop()
- func (s *Session) Text(ctx context.Context, ref string, max int) (string, error)
- func (s *Session) Title(ctx context.Context) (string, error)
- func (s *Session) Type(ctx context.Context, ref, text string, submit bool) (string, error)
- func (s *Session) URL(ctx context.Context) (string, error)
- func (s *Session) Upload(ctx context.Context, ref, path string) (string, error)
- func (s *Session) WaitFor(ctx context.Context, text string, timeout time.Duration) (string, error)
- func (s *Session) WaitForSelector(ctx context.Context, sel string, timeout time.Duration) error
- func (s *Session) WaitReady(ctx context.Context, timeout time.Duration) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FindExecutable ¶
FindExecutable returns the first usable Chrome on this machine.
Types ¶
type Cookie ¶
type Cookie struct {
Name string `json:"name"`
Value string `json:"value"`
Domain string `json:"domain,omitempty"`
Path string `json:"path,omitempty"`
Expires float64 `json:"expires,omitempty"` // CDP uses seconds-since-epoch as float
Size int `json:"size,omitempty"`
HTTPOnly bool `json:"httpOnly,omitempty"`
Secure bool `json:"secure,omitempty"`
SameSite string `json:"sameSite,omitempty"`
Session bool `json:"session,omitempty"`
}
Cookie is one browser cookie, in the shape CDP returns/expects.
type NetworkRequest ¶
type NetworkRequest struct {
RequestID string
Method string
URL string
Headers map[string]string
PostData string // request body, when the page supplied one
// Response is populated when a matching responseReceived event fired
// before DrainNetwork ran. Nil for failed requests and pre-flight
// CORS checks that never landed.
Response *NetworkResponse
// Failed is non-empty when the request errored (net::ERR_CONNECTION_REFUSED,
// CORS block, etc). A request with neither Response nor Failed is still
// in flight or was cancelled mid-action.
Failed string
}
NetworkRequest is one HTTP request the page issued, paired with its response when one was received. Populated by draining CDP Network.* events via DrainNetwork.
type NetworkResponse ¶
type NetworkResponse struct {
Status int
URL string // may differ from request URL after redirects
Headers map[string]string
// MIME type from response.headers.content-type, captured for filtering.
MIMEType string
// RemoteIP is the server address Chrome connected to. Empty for
// service-worker responses and opaque origins.
RemoteIP string
}
NetworkResponse is the wire-level response to a NetworkRequest.
type Options ¶
type Options struct {
// Executable overrides Chrome discovery.
Executable string
// UserDataDir persists cookies and logins between runs.
UserDataDir string
// Headless runs without a visible window; false needs a display.
Headless bool
// Width and Height set the viewport.
Width, Height int
// RemoteURL attaches to an already-running Chrome instead of starting one,
// e.g. "http://127.0.0.1:9222".
RemoteURL string
// Stealth launches a source-patched anti-detection Chromium (downloaded and
// verified on first use) instead of the system Chrome, so pages guarded by
// bot-detection challenges (Cloudflare Turnstile and the like) load. It has
// no effect when RemoteURL is set — that attaches to a browser already
// running.
Stealth bool
// Proxy routes the stealth browser through a proxy, e.g.
// "http://host:3128" or "socks5://host:1080".
Proxy string
// Timezone and Locale spoof the stealth browser's fingerprint, e.g.
// "America/New_York" and "en-US".
Timezone string
Locale string
}
Options configure how a browser is started.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is one browser with one active page. Keeping the page alive between tool calls is the whole point: an agent clicks, reads, and clicks again without re-navigating and losing its login.
func (*Session) ClickSelector ¶
ClickSelector scrolls the element matching sel into view and clicks it through the DOM node — works with React-style event delegation that ignores synthetic MouseEvents.
Returns one of:
- "ok" : the click was dispatched
- "gone" : no element matched sel
- "hidden" : the element is display:none / visibility:hidden / opacity:0
A click is fire-and-forget at the DOM level; if it triggers navigation or async work, wait for the document to settle separately.
func (*Session) ClickXY ¶
ClickXY sends a real mouse press+release at viewport coordinates. Some widgets (a Turnstile checkbox living in a cross-origin iframe) can only be reached this way, and score a synthetic DOM .click() as fake — a dispatched mouse event at the right point is what they accept.
func (*Session) Cookies ¶
Cookies returns every cookie for the URLs given (or all cookies if none are passed). The URLs let CDP pick up partitioned/host-only cookies that a bare getCookies would miss.
func (*Session) DrainNetwork ¶
func (s *Session) DrainNetwork(ctx context.Context) []NetworkRequest
DrainNetwork pulls every buffered Network.* event out of the CDP client and returns one NetworkRequest per requestID, with request and response data merged. Failed requests carry their error string.
The returned slice is in arrival order of requestWillBeSent; responses are correlated by requestID. Requests whose response hasn't landed yet are still returned with Response == nil — callers can re-drain later or accept the partial picture, depending on how long they waited.
DrainNetwork is destructive: a second call returns only what arrived in between. The pattern is "run an action, then drain".
func (*Session) EvalFunc ¶
EvalFunc runs `(function(...args){ body })(arg1, arg2, ...)` — for callers that prefer passing arguments out-of-line rather than interpolating them into the body string. Each arg is JSON-encoded.
func (*Session) EvalString ¶
EvalString runs JavaScript expected to produce a string.
func (*Session) FillSelector ¶
FillSelector sets the value of an input matched by sel, dispatching input/change events the way React/Vue expect (via the prototype setter on HTMLInputElement/HTMLTextAreaElement). Clears the field first.
Returns "ok", "gone" (selector matched nothing), or "readonly" (the field refuses writes — typical of type=hidden or explicitly readonly).
func (*Session) InsertText ¶
InsertText types text into the focused element as if a human had.
func (*Session) PressSelector ¶
PressSelector waits for sel to appear (up to timeout), then triggers a keydown+keyup on it. Useful for submit-button-like elements that listen for keyboard events rather than click.
func (*Session) ResponseBody ¶
func (s *Session) ResponseBody(ctx context.Context, requestID string) (body string, mimeType string, err error)
ResponseBody fetches the body of a finished response by requestID. Returns (body, mimeType, error). The body may be empty for responses that were discarded (large, opaque, or already evicted from Chrome's buffer), so callers should treat an empty string + nil error as "no body available" rather than as a successful empty body.
Chrome evicts response bodies aggressively; this method works reliably only when called shortly after the response arrives.
func (*Session) Screenshot ¶
Screenshot captures the viewport as PNG bytes.
func (*Session) SetCookies ¶
SetCookies replaces the cookie jar with the given cookies. Existing cookies with the same (name, domain, path) tuple are overwritten.
func (*Session) Upload ¶ added in v0.4.0
Upload attaches a local file to the <input type="file"> element pointed to by the snapshot reference `ref` (e.g. "e7"). It is the native browser upload path — DOM.setFileInputFiles pushes the bytes at CDP level, so no fake keystrokes or drag-and-drop dances are needed and React/Vue onChange handlers fire exactly the same way they would for a human file-picker.
The caller (tool layer) authorizes the path; here we only sanity-check that the file exists and is readable, so a broken path fails with a legible error before the CDP call.
Some publisher UIs hide the real <input type=file> behind a styled button that clicks it on demand. When the ref points at such a container, this function walks one level of DOM (the ref itself, then its subtree, then a nearby form/section) looking for a file input. It refuses to upload against anything else — a text input, a link, a div — so the mistake is visible.
func (*Session) WaitForSelector ¶
WaitForSelector polls until sel matches something in the DOM, or the timeout elapses. Returns nil when found, an error otherwise.