browser

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 18 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 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

Constants

This section is empty.

Variables

This section is empty.

Functions

func FindExecutable

func FindExecutable(override string) (string, error)

FindExecutable returns the first usable Chrome on this machine.

Types

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 New

func New(opts Options) *Session

New builds an unstarted session.

func (*Session) Back

func (s *Session) Back(ctx context.Context) error

Back goes to the previous page in history.

func (*Session) Click

func (s *Session) Click(ctx context.Context, ref string) (string, error)

Click activates a referenced element, scrolling it into view first.

func (*Session) ClickSelector

func (s *Session) ClickSelector(ctx context.Context, sel string) (string, error)

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

func (s *Session) ClickXY(ctx context.Context, x, y float64) error

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) Console

func (s *Session) Console() []string

Console drains buffered console output.

func (*Session) Cookies

func (s *Session) Cookies(ctx context.Context, urls ...string) ([]Cookie, error)

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) Eval

func (s *Session) Eval(ctx context.Context, expression string) (json.RawMessage, error)

Eval runs JavaScript in the page and returns its value as JSON.

func (*Session) EvalFunc

func (s *Session) EvalFunc(ctx context.Context, body string, args ...any) (json.RawMessage, error)

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

func (s *Session) EvalString(ctx context.Context, expression string) (string, error)

EvalString runs JavaScript expected to produce a string.

func (*Session) FillSelector

func (s *Session) FillSelector(ctx context.Context, sel, value string) (string, error)

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

func (s *Session) InsertText(ctx context.Context, text string) error

InsertText types text into the focused element as if a human had.

func (*Session) LastUsed

func (s *Session) LastUsed() time.Time

LastUsed is when a command last ran, for idle reaping.

func (*Session) Navigate

func (s *Session) Navigate(ctx context.Context, url string) error

Navigate loads a URL and waits for the page to settle.

func (*Session) PressKey

func (s *Session) PressKey(ctx context.Context, key string) error

PressKey sends one key to the focused element.

func (*Session) PressSelector

func (s *Session) PressSelector(ctx context.Context, sel, key string, timeout time.Duration) error

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) Requests

func (s *Session) Requests() []string

Requests drains the buffered network log.

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

func (s *Session) Screenshot(ctx context.Context, fullPage bool) ([]byte, error)

Screenshot captures the viewport as PNG bytes.

func (*Session) Scroll

func (s *Session) Scroll(ctx context.Context, direction string, amount int) (string, error)

Scroll moves the page or a referenced element.

func (*Session) Select

func (s *Session) Select(ctx context.Context, ref, value string) (string, error)

Select picks an option in a referenced <select> by value or visible label.

func (*Session) SetCookies

func (s *Session) SetCookies(ctx context.Context, cookies []Cookie) error

SetCookies replaces the cookie jar with the given cookies. Existing cookies with the same (name, domain, path) tuple are overwritten.

func (*Session) Snapshot

func (s *Session) Snapshot(ctx context.Context, max int) (string, error)

Snapshot returns a compact, referenced view of what is on the page.

func (*Session) Start

func (s *Session) Start(ctx context.Context) error

func (*Session) Started

func (s *Session) Started() bool

Started reports whether a browser is running.

func (*Session) Stop

func (s *Session) Stop()

Stop closes the page and the browser it started.

func (*Session) Text

func (s *Session) Text(ctx context.Context, ref string, max int) (string, error)

Text extracts the readable text of the page, or of one referenced element.

func (*Session) Title

func (s *Session) Title(ctx context.Context) (string, error)

Title reports the page title.

func (*Session) Type

func (s *Session) Type(ctx context.Context, ref, text string, submit bool) (string, error)

Type focuses a referenced field and enters text into it.

func (*Session) URL

func (s *Session) URL(ctx context.Context) (string, error)

URL reports where the page currently is.

func (*Session) Upload added in v0.4.0

func (s *Session) Upload(ctx context.Context, ref, path string) (string, error)

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) WaitFor

func (s *Session) WaitFor(ctx context.Context, text string, timeout time.Duration) (string, error)

WaitFor polls until text appears on the page or the budget runs out.

func (*Session) WaitForSelector

func (s *Session) WaitForSelector(ctx context.Context, sel string, timeout time.Duration) error

WaitForSelector polls until sel matches something in the DOM, or the timeout elapses. Returns nil when found, an error otherwise.

func (*Session) WaitReady

func (s *Session) WaitReady(ctx context.Context, timeout time.Duration) error

WaitReady blocks until the document has finished parsing, or the timeout passes. A page that never settles is still usable, so a timeout is not an error the caller has to handle.

Jump to

Keyboard shortcuts

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