browser

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2026 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatCookies

func FormatCookies(cookies []CookieInfo) string

FormatCookies formats cookies as human-readable text.

func FormatNetworkRequests

func FormatNetworkRequests(reqs []NetworkRequest) string

FormatNetworkRequests formats network request list as human-readable text.

func FormatStorage

func FormatStorage(items map[string]string) string

FormatStorage formats a storage map as human-readable text.

func FormatTabList

func FormatTabList(tabs []TabInfo) string

FormatTabList formats the tab list as human-readable text.

Types

type BoxResult

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

BoxResult holds the bounding box of an element.

type Browser

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

func Connect

func Connect(target string, opts Options) (*Browser, error)

Connect connects to an already-running Chrome instance via CDP. The target can be:

  • A port number string like "9222" → connects to http://localhost:9222
  • A WebSocket URL like "ws://localhost:9222/devtools/browser/..."
  • A remote WebSocket URL like "wss://remote.example.com/cdp?token=..."

func New

func New(opts Options) (*Browser, error)

func (*Browser) ApplyState

func (b *Browser) ApplyState(state *BrowserState) error

ApplyState applies a BrowserState to the current browser session.

func (*Browser) Back

func (b *Browser) Back() error

func (*Browser) Check

func (b *Browser) Check(id int) error

func (*Browser) ClearGeo

func (b *Browser) ClearGeo() error

ClearGeo removes the geolocation override.

func (*Browser) Click

func (b *Browser) Click(id int) error

func (*Browser) ClickNewTab

func (b *Browser) ClickNewTab(id int) error

ClickNewTab clicks a link element and opens it in a new tab. This works by setting target="_blank" temporarily and clicking.

func (*Browser) ClipboardCopy

func (b *Browser) ClipboardCopy() error

ClipboardCopy simulates Ctrl+C (or Cmd+C on macOS) to copy the current selection.

func (*Browser) ClipboardPaste

func (b *Browser) ClipboardPaste() error

ClipboardPaste simulates Ctrl+V (or Cmd+V on macOS) to paste from clipboard.

func (*Browser) ClipboardRead

func (b *Browser) ClipboardRead() (string, error)

ClipboardRead reads text content from the clipboard. Uses the Clipboard API via JavaScript with CDP permissions override.

func (*Browser) ClipboardWrite

func (b *Browser) ClipboardWrite(text string) error

ClipboardWrite writes text to the clipboard.

func (*Browser) Close

func (b *Browser) Close()

func (*Browser) ConsoleClear

func (b *Browser) ConsoleClear()

ConsoleClear clears all collected console messages.

func (*Browser) ConsoleMessages

func (b *Browser) ConsoleMessages() ([]ConsoleMessage, error)

ConsoleMessages returns all collected console messages. Call ConsoleStart() first to begin listening.

func (*Browser) ConsoleMessagesByLevel

func (b *Browser) ConsoleMessagesByLevel(level string) ([]ConsoleMessage, error)

ConsoleMessagesByLevel returns console messages filtered by level. Levels: "log", "warning", "error", "info", "debug"

func (*Browser) ConsoleStart

func (b *Browser) ConsoleStart() error

ConsoleStart begins collecting console messages and page errors.

func (*Browser) Context

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

func (*Browser) CookieDelete

func (b *Browser) CookieDelete(name string) error

CookieDelete deletes a cookie by name.

func (*Browser) CookieSet

func (b *Browser) CookieSet(cookie CookieInfo) error

CookieSet sets a cookie. At minimum, name and value are required. Domain defaults to the current page's domain if empty.

func (*Browser) CookiesClear

func (b *Browser) CookiesClear() error

CookiesClear clears all cookies.

func (*Browser) CookiesGet

func (b *Browser) CookiesGet() ([]CookieInfo, error)

CookiesGet returns all cookies for the current page.

func (*Browser) DblClick

func (b *Browser) DblClick(id int) error

func (*Browser) DiffScreenshot

func (b *Browser) DiffScreenshot(opts DiffScreenshotOptions) (*DiffScreenshotResult, error)

DiffScreenshot performs a pixel-level comparison between the current page screenshot and a baseline PNG image.

func (*Browser) DiffSnapshot

func (b *Browser) DiffSnapshot(opts ...DiffSnapshotOptions) (*DiffSnapshotResult, error)

DiffSnapshot compares the current page snapshot with a baseline. If opts.BaselineFile is empty, compares with the previous Snapshot() result. Returns a unified diff of the two snapshots.

func (*Browser) DiffURL

func (b *Browser) DiffURL(url1, url2 string, opts ...DiffURLOptions) (*DiffURLResult, error)

DiffURL navigates to two URLs and compares their snapshots (and optionally screenshots). This method navigates the browser to url1, takes a snapshot, then navigates to url2 and takes another snapshot, then computes the diff.

func (*Browser) Download

func (b *Browser) Download(id int, saveDir string, opts ...DownloadOptions) (string, error)

Download clicks a download link/button and saves the file to the specified directory. Returns the path to the downloaded file.

func (*Browser) Drag

func (b *Browser) Drag(srcID, dstID int) error

Drag performs a drag-and-drop from the source element to the destination element. Both srcID and dstID are display IDs from the latest snapshot.

func (*Browser) DragCoords

func (b *Browser) DragCoords(srcX, srcY, dstX, dstY float64) error

DragCoords performs a drag-and-drop from (srcX, srcY) to (dstX, dstY) in page coordinates.

func (*Browser) Eval

func (b *Browser) Eval(expression string) (string, error)

Eval evaluates a JavaScript expression in the page context and returns the result as a string. For complex objects, the result is JSON-encoded.

func (*Browser) ExportState

func (b *Browser) ExportState(outputPath string) error

ExportState exports the current browser state (cookies + localStorage) to a JSON file.

func (*Browser) Fill

func (b *Browser) Fill(id int, text string) error

func (*Browser) FindAlt

func (b *Browser) FindAlt(text string, opts ...FindOption) (*FindResults, error)

FindAlt searches for elements (typically images) whose name matches the alt text.

func (*Browser) FindFirst

func (b *Browser) FindFirst(cssSelector string) (*FindResults, error)

FindFirst returns the first element matching the given CSS selector.

func (*Browser) FindLabel

func (b *Browser) FindLabel(label string, opts ...FindOption) (*FindResults, error)

FindLabel searches for form elements associated with the given label text.

func (*Browser) FindLast

func (b *Browser) FindLast(cssSelector string) (*FindResults, error)

FindLast returns the last element matching the given CSS selector.

func (*Browser) FindNth

func (b *Browser) FindNth(cssSelector string, n int) (*FindResults, error)

FindNth returns the nth match (1-based) from a CSS selector query. This operates on the DOM, not the snapshot.

func (*Browser) FindPlaceholder

func (b *Browser) FindPlaceholder(text string, opts ...FindOption) (*FindResults, error)

FindPlaceholder searches for elements by placeholder attribute via DOM query.

func (*Browser) FindRole

func (b *Browser) FindRole(role string, name string, opts ...FindOption) (*FindResults, error)

FindRole searches the latest snapshot for elements with the given role. If name is non-empty, only elements whose name contains name (case-insensitive) are returned. If exact is true, the name must match exactly.

func (*Browser) FindTestID

func (b *Browser) FindTestID(testID string) (*FindResults, error)

FindTestID searches for elements by data-testid attribute. This operates on the DOM, not the snapshot.

func (*Browser) FindText

func (b *Browser) FindText(text string, opts ...FindOption) (*FindResults, error)

FindText searches the latest snapshot for elements whose name contains the given text.

func (*Browser) FindTitle

func (b *Browser) FindTitle(text string, opts ...FindOption) (*FindResults, error)

FindTitle searches for elements by title attribute via DOM query.

func (*Browser) Focus

func (b *Browser) Focus(id int) error

func (*Browser) Forward

func (b *Browser) Forward() error

func (*Browser) GetAttr

func (b *Browser) GetAttr(id int, name string) (string, error)

GetAttr returns the value of an HTML attribute on the element.

func (*Browser) GetBox

func (b *Browser) GetBox(id int) (*BoxResult, error)

GetBox returns the bounding box of the element with the given display ID.

func (*Browser) GetCDPURL

func (b *Browser) GetCDPURL() (string, error)

GetCDPURL returns the CDP WebSocket URL for the current browser session. This queries the browser target's URL from the active context.

func (*Browser) GetCount

func (b *Browser) GetCount(cssSelector string) (int, error)

GetCount returns the number of elements matching a CSS selector.

func (*Browser) GetHTML

func (b *Browser) GetHTML(id int) (string, error)

GetHTML returns the inner HTML of the element with the given display ID. For void elements (input, img, br, etc.) where innerHTML is always empty, it returns outerHTML instead.

func (*Browser) GetStyles

func (b *Browser) GetStyles(id int) (string, error)

GetStyles returns selected computed styles of the element as a JSON string.

func (*Browser) GetText

func (b *Browser) GetText(id int) (string, error)

GetText returns the inner text of the element with the given display ID. For form elements (input, textarea, select), it returns the value or placeholder.

func (*Browser) GetTitle

func (b *Browser) GetTitle() (string, error)

GetTitle returns the current page title.

func (*Browser) GetURL

func (b *Browser) GetURL() (string, error)

GetURL returns the current page URL.

func (*Browser) GetValue

func (b *Browser) GetValue(id int) (string, error)

GetValue returns the value of a form element with the given display ID.

func (*Browser) Highlight

func (b *Browser) Highlight(id int) error

Highlight visually highlights the element with the given snapshot ID. The highlight is shown temporarily with a colored border.

func (*Browser) Hover

func (b *Browser) Hover(id int) error

func (*Browser) ImportState

func (b *Browser) ImportState(inputPath string) error

ImportState imports browser state (cookies + localStorage) from a JSON file.

func (*Browser) IsChecked

func (b *Browser) IsChecked(id int) (bool, error)

IsChecked returns true if the element is checked.

func (*Browser) IsEnabled

func (b *Browser) IsEnabled(id int) (bool, error)

IsEnabled returns true if the element is not disabled.

func (*Browser) IsVisible

func (b *Browser) IsVisible(id int) (bool, error)

IsVisible returns true if the element is visible (has non-zero size and not hidden).

func (*Browser) KeyboardInsertText

func (b *Browser) KeyboardInsertText(text string) error

KeyboardInsertText inserts text without triggering keyboard events (keydown/keypress/keyup). This is similar to pasting text and is useful for rich text editors.

func (*Browser) KeyboardType

func (b *Browser) KeyboardType(text string) error

func (*Browser) MouseClick

func (b *Browser) MouseClick(x, y float64, opts ...MouseOptions) error

MouseClick performs a full click (move + down + up) at the given coordinates.

func (*Browser) MouseDown

func (b *Browser) MouseDown(x, y float64, opts ...MouseOptions) error

MouseDown presses a mouse button at the current position (or the given coordinates).

func (*Browser) MouseMove

func (b *Browser) MouseMove(x, y float64) error

MouseMove moves the mouse to the given page coordinates (x, y).

func (*Browser) MouseUp

func (b *Browser) MouseUp(x, y float64, opts ...MouseOptions) error

MouseUp releases a mouse button at the given coordinates.

func (*Browser) MouseWheel

func (b *Browser) MouseWheel(x, y float64, deltaX, deltaY float64) error

MouseWheel dispatches a mouse wheel event at the given coordinates. deltaX scrolls horizontally (positive = right), deltaY scrolls vertically (positive = down).

func (*Browser) NetworkClearRequests

func (b *Browser) NetworkClearRequests()

NetworkClearRequests clears all recorded network requests.

func (*Browser) NetworkRequests

func (b *Browser) NetworkRequests() ([]NetworkRequest, error)

NetworkRequests returns a list of recorded network requests. Call NetworkStartLogging() first to begin recording.

func (*Browser) NetworkRoute

func (b *Browser) NetworkRoute(pattern string, action RouteAction) error

NetworkRoute registers a route pattern to intercept requests. Matching requests will be handled based on the action:

  • RouteBlock: the request is failed (blocked)
  • RouteContinue: the request is allowed through

func (*Browser) NetworkStartLogging

func (b *Browser) NetworkStartLogging() error

NetworkStartLogging enables recording of network requests.

func (*Browser) NetworkUnroute

func (b *Browser) NetworkUnroute(pattern string) error

NetworkUnroute removes a previously registered route pattern.

func (*Browser) Open

func (b *Browser) Open(url string) error

func (*Browser) OpenDevTools

func (b *Browser) OpenDevTools() error

OpenDevTools sends an inspector open request via CDP. Note: this only works when the browser is NOT in headless mode.

func (*Browser) PDF

func (b *Browser) PDF(path string, opts ...PDFOptions) error

PDF generates a PDF of the current page and saves it to path.

func (*Browser) PageErrors

func (b *Browser) PageErrors() ([]PageError, error)

PageErrors returns all collected JavaScript exceptions. Call ConsoleStart() first to begin listening.

func (*Browser) PageErrorsClear

func (b *Browser) PageErrorsClear()

PageErrorsClear clears all collected page errors.

func (*Browser) Press

func (b *Browser) Press(key string) error

func (*Browser) ProfilerStart

func (b *Browser) ProfilerStart() error

ProfilerStart begins CPU profiling.

func (*Browser) ProfilerStop

func (b *Browser) ProfilerStop(outputPath string) error

ProfilerStop stops CPU profiling and saves the result to the given path. The output is a JSON file in the Chrome DevTools CPU Profile format.

func (*Browser) RecordStart

func (b *Browser) RecordStart(outputPath string) error

RecordStart begins recording screenshots (screencast frames) from the browser. The frames are collected as PNG images. When stopped, they are saved to the output path. For simplicity, the recording captures individual frames rather than encoding a video format. The output is saved as a series of PNG files or as a concatenated binary.

func (*Browser) RecordStop

func (b *Browser) RecordStop() (int, error)

RecordStop stops the recording and saves the captured frames. Frames are saved as individual PNG files: {outputPath}_001.png, {outputPath}_002.png, etc. Returns the number of frames captured.

func (*Browser) Reload

func (b *Browser) Reload() error

func (*Browser) Screenshot

func (b *Browser) Screenshot(path string, opts ...ScreenshotOptions) error

Screenshot captures a screenshot and saves it to the given path. Supported formats: .png (default) and .jpg/.jpeg.

func (*Browser) ScreenshotAnnotated

func (b *Browser) ScreenshotAnnotated(path string, opts ...ScreenshotOptions) error

ScreenshotAnnotated captures a screenshot with snapshot element IDs overlaid as numbered badges near each interactive element. This is useful for AI agents that need to correlate visual positions with snapshot IDs.

func (*Browser) ScreenshotToBytes

func (b *Browser) ScreenshotToBytes(opts ...ScreenshotOptions) ([]byte, error)

ScreenshotToBytes captures a screenshot and returns the raw bytes.

func (*Browser) Scroll

func (b *Browser) Scroll(direction string, pixels int) error

func (*Browser) ScrollIntoView

func (b *Browser) ScrollIntoView(id int) error

func (*Browser) Select

func (b *Browser) Select(id int, values ...string) error

func (*Browser) SetColorScheme

func (b *Browser) SetColorScheme(scheme string) error

SetColorScheme is a convenience method for SetMedia with prefers-color-scheme.

func (*Browser) SetCredentials

func (b *Browser) SetCredentials(user, pass string) error

SetCredentials sets HTTP Basic Auth credentials for all requests. The credentials are injected via extra HTTP headers (Authorization).

func (*Browser) SetDevice

func (b *Browser) SetDevice(name string) error

SetDevice emulates a specific device by name (e.g., "iPhone 12", "Pixel 5"). Returns error if the device is not recognized.

func (*Browser) SetGeo

func (b *Browser) SetGeo(lat, lon float64) error

SetGeo overrides geolocation to the specified latitude and longitude. Use accuracy > 0 for a more precise emulation; defaults to 1 meter.

func (*Browser) SetHeaders

func (b *Browser) SetHeaders(headers map[string]string) error

SetHeaders sets extra HTTP headers to be sent with every request.

func (*Browser) SetMedia

func (b *Browser) SetMedia(features ...MediaFeature) error

SetMedia sets the emulated CSS media type and/or color scheme. media can be "screen", "print", or "". colorScheme can be "dark", "light", or "".

func (*Browser) SetOffline

func (b *Browser) SetOffline(offline bool) error

SetOffline enables or disables offline mode by emulating network conditions.

func (*Browser) SetViewport

func (b *Browser) SetViewport(width, height int, scale ...float64) error

SetViewport sets the browser viewport size with optional device scale factor. If scale is not provided or is 0, defaults to 1.0.

func (*Browser) Snapshot

func (b *Browser) Snapshot(opts ...SnapshotOptions) (*SnapshotResult, error)

func (*Browser) StorageClear

func (b *Browser) StorageClear(storageType string) error

StorageClear clears all items in localStorage or sessionStorage.

func (*Browser) StorageDelete

func (b *Browser) StorageDelete(storageType, key string) error

StorageDelete removes a key from localStorage or sessionStorage.

func (*Browser) StorageGet

func (b *Browser) StorageGet(storageType, key string) (string, error)

StorageGet gets a value from localStorage or sessionStorage. storageType should be "local" or "session".

func (*Browser) StorageGetAll

func (b *Browser) StorageGetAll(storageType string) (map[string]string, error)

StorageGetAll returns all key-value pairs from localStorage or sessionStorage.

func (*Browser) StorageSet

func (b *Browser) StorageSet(storageType, key, value string) error

StorageSet sets a value in localStorage or sessionStorage. storageType should be "local" or "session".

func (*Browser) TabClose

func (b *Browser) TabClose(index int) error

TabClose closes the tab at the given index (from TabList). If index is -1, closes the current tab.

func (*Browser) TabList

func (b *Browser) TabList() ([]TabInfo, error)

TabList returns information about all open tabs. It queries the browser via CDP to discover ALL actual tabs, not just the ones tracked in b.tabs.

func (*Browser) TabNew

func (b *Browser) TabNew(url string) error

TabNew opens a new tab with the given URL and switches to it. If url is empty, opens about:blank.

func (*Browser) TabSwitch

func (b *Browser) TabSwitch(index int) error

TabSwitch switches to the tab at the given index (from TabList).

func (*Browser) TraceStart

func (b *Browser) TraceStart(categories ...string) error

TraceStart begins recording a Chrome trace. Categories is an optional comma-separated list of tracing categories. If empty, default categories are used.

func (*Browser) TraceStop

func (b *Browser) TraceStop(outputPath string) error

TraceStop stops the trace recording and saves the trace data to the given path. The output is a JSON file that can be loaded in chrome://tracing or Perfetto UI.

func (*Browser) Type

func (b *Browser) Type(id int, text string) error

func (*Browser) Uncheck

func (b *Browser) Uncheck(id int) error

func (*Browser) Upload

func (b *Browser) Upload(id int, files ...string) error

Upload sets files on a file input element identified by display ID. The element must be an <input type="file"> element, or a label associated with one. If the element is not a file input, Upload will attempt to find an associated file input (e.g., via label's "for" attribute or child input).

func (*Browser) UploadCSS

func (b *Browser) UploadCSS(cssSelector string, files ...string) error

UploadCSS sets files on a file input element identified by CSS selector.

func (*Browser) Wait

func (b *Browser) Wait(d time.Duration) error

func (*Browser) WaitDownload

func (b *Browser) WaitDownload(savePath string, timeout ...time.Duration) (string, error)

WaitDownload sets up a download handler, waits for a download event, and saves the file. The savePath is the directory where the downloaded file will be saved. Returns the downloaded file path.

func (*Browser) WaitFunc

func (b *Browser) WaitFunc(expression string, timeout ...time.Duration) error

WaitFunc waits until the given JavaScript expression evaluates to a truthy value.

func (*Browser) WaitHidden

func (b *Browser) WaitHidden(cssSelector string, timeout ...time.Duration) error

WaitHidden waits for an element matching the CSS selector to become hidden or removed from the DOM.

func (*Browser) WaitLoad

func (b *Browser) WaitLoad(timeout ...time.Duration) error

WaitLoad waits until the page reaches the "load" state (document.readyState === "complete").

func (*Browser) WaitSelector

func (b *Browser) WaitSelector(cssSelector string, timeout ...time.Duration) error

WaitSelector waits for an element matching the CSS selector to appear in the DOM.

func (*Browser) WaitText

func (b *Browser) WaitText(text string, timeout ...time.Duration) error

WaitText waits until the given text appears somewhere in the page body.

func (*Browser) WaitURL

func (b *Browser) WaitURL(pattern string, timeout ...time.Duration) error

WaitURL waits until the page URL contains the given substring.

type BrowserState

type BrowserState struct {
	Cookies      []CookieInfo      `json:"cookies,omitempty"`
	LocalStorage map[string]string `json:"localStorage,omitempty"`
	// Origin is the URL origin used for localStorage operations.
	Origin string `json:"origin,omitempty"`
}

BrowserState represents the serializable state of a browser session, including cookies and localStorage data.

type ConsoleMessage

type ConsoleMessage struct {
	Level     string `json:"level"` // "log", "warning", "error", "info", "debug"
	Text      string `json:"text"`
	Timestamp int64  `json:"timestamp,omitempty"`
}

ConsoleMessage represents a single console log message.

type CookieInfo

type CookieInfo struct {
	Name     string  `json:"name"`
	Value    string  `json:"value"`
	Domain   string  `json:"domain"`
	Path     string  `json:"path"`
	Expires  float64 `json:"expires,omitempty"`
	HTTPOnly bool    `json:"httpOnly,omitempty"`
	Secure   bool    `json:"secure,omitempty"`
	SameSite string  `json:"sameSite,omitempty"`
	URL      string  `json:"url,omitempty"`
}

CookieInfo represents a browser cookie.

type DeviceDescriptor

type DeviceDescriptor struct {
	Name      string
	Width     int64
	Height    int64
	Scale     float64
	Mobile    bool
	UserAgent string
}

DeviceDescriptor describes a device for emulation.

type DiffScreenshotOptions

type DiffScreenshotOptions struct {
	// BaselineFile is the path to a baseline PNG image (required).
	BaselineFile string
	// OutputPath is the path to save the diff image. If empty, no diff image is saved.
	OutputPath string
	// Threshold is the color distance threshold (0-1). Default: 0.1.
	// Pixels with a normalized distance below this are considered identical.
	Threshold float64
	// FullPage captures the full scrollable page.
	FullPage bool
	// ElementID if > 0, capture only this element for comparison.
	ElementID int
}

DiffScreenshotOptions configures screenshot diff behavior.

type DiffScreenshotResult

type DiffScreenshotResult struct {
	// DiffCount is the number of pixels that differ.
	DiffCount int `json:"diffCount"`
	// TotalPixels is the total number of pixels compared.
	TotalPixels int `json:"totalPixels"`
	// DiffPercent is the percentage of differing pixels (0-100).
	DiffPercent float64 `json:"diffPercent"`
	// Changed is true if there are any pixel differences above threshold.
	Changed bool `json:"changed"`
	// DiffImage holds the diff image bytes (PNG), if OutputPath was set.
	DiffImage []byte `json:"-"`
}

DiffScreenshotResult holds the result of a pixel-level screenshot comparison.

type DiffSnapshotOptions

type DiffSnapshotOptions struct {
	// BaselineFile is the path to a saved baseline snapshot file.
	// If empty, the previous snapshot (lastSnap) is used as baseline.
	BaselineFile string
	// SnapshotOptions for taking the current snapshot.
	SnapshotOptions SnapshotOptions
}

DiffSnapshotOptions configures snapshot diff behavior.

type DiffSnapshotResult

type DiffSnapshotResult struct {
	// Text is the unified diff output.
	Text string `json:"text"`
	// Added is the number of added lines.
	Added int `json:"added"`
	// Removed is the number of removed lines.
	Removed int `json:"removed"`
	// Changed is true if there are any differences.
	Changed bool `json:"changed"`
}

DiffSnapshotResult holds the result of comparing two accessibility snapshots.

type DiffURLOptions

type DiffURLOptions struct {
	// IncludeScreenshot also compares screenshots, not just snapshots.
	IncludeScreenshot bool
	// FullPage captures full page screenshots.
	FullPage bool
	// SnapshotOptions for taking snapshots.
	SnapshotOptions SnapshotOptions
	// Threshold for screenshot comparison (0-1). Default: 0.1.
	Threshold float64
}

DiffURLOptions configures URL comparison behavior.

type DiffURLResult

type DiffURLResult struct {
	// SnapshotDiff is the snapshot comparison result.
	SnapshotDiff *DiffSnapshotResult `json:"snapshotDiff"`
	// ScreenshotDiff is the screenshot comparison result (if requested).
	ScreenshotDiff *DiffScreenshotResult `json:"screenshotDiff,omitempty"`
}

DiffURLResult holds the result of comparing two URLs.

type DownloadOptions

type DownloadOptions struct {
	Timeout time.Duration // timeout waiting for download to complete (default: 30s)
}

DownloadOptions controls download behavior.

type FindOption

type FindOption func(*findConfig)

FindOption configures find behavior.

func WithExact

func WithExact() FindOption

WithExact enables exact matching instead of substring matching.

type FindResult

type FindResult struct {
	ID   int    // display ID from the snapshot
	Role string // semantic role
	Name string // accessible name
}

FindResult represents a found element in the accessibility tree.

type FindResults

type FindResults struct {
	Items []FindResult
	Text  string // formatted text for CLI output
}

FindResults holds the results of a find operation along with a formatted text view.

type MediaFeature

type MediaFeature struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

MediaFeature represents a CSS media feature to emulate.

type MouseButton

type MouseButton string

MouseButton specifies a mouse button.

const (
	MouseLeft   MouseButton = "left"
	MouseRight  MouseButton = "right"
	MouseMiddle MouseButton = "middle"
)

type MouseOptions

type MouseOptions struct {
	Button MouseButton // button for down/up (default: left)
}

MouseOptions configures a mouse action.

type NetworkRequest

type NetworkRequest struct {
	URL        string `json:"url"`
	Method     string `json:"method"`
	Status     int64  `json:"status"`
	StatusText string `json:"statusText,omitempty"`
	Type       string `json:"type,omitempty"`
}

NetworkRequest records information about a completed network request.

type Options

type Options struct {
	Headless bool
	Timeout  time.Duration
	Logf     func(string, ...any)

	// Profile is a path to a Chrome user data directory for persistent sessions.
	// When set, cookies, IndexedDB, cache, etc. are preserved across restarts.
	Profile string

	// StatePath is a path to a JSON file containing saved browser state
	// (cookies + localStorage) to import when creating the browser.
	StatePath string

	UserAgent         string   // custom User-Agent string
	Proxy             string   // proxy server URL (e.g. "http://proxy:8080" or "socks5://proxy:1080")
	ProxyBypass       string   // comma-separated hosts to bypass proxy
	IgnoreHTTPSErrors bool     // ignore HTTPS certificate errors
	AllowFileAccess   bool     // allow file:// URL access across origins
	Extensions        []string // paths to Chrome extension directories to load
	ExtraArgs         []string // extra Chrome command-line arguments
	DownloadPath      string   // default download directory
	ScreenshotDir     string   // default screenshot output directory
	ScreenshotFormat  string   // default screenshot format: "png" or "jpeg"
}

func DefaultOptions

func DefaultOptions() Options

type PDFOptions

type PDFOptions struct {
	Landscape   bool
	PrintBG     bool    // print background graphics
	PaperWidth  float64 // inches, default 8.5
	PaperHeight float64 // inches, default 11
}

PDFOptions controls PDF generation.

type PageError

type PageError struct {
	Message string `json:"message"`
	URL     string `json:"url,omitempty"`
	Line    int    `json:"line,omitempty"`
	Column  int    `json:"column,omitempty"`
}

PageError represents a JavaScript exception caught on the page.

type RouteAction

type RouteAction int

RouteAction defines what to do with a matched request.

const (
	RouteBlock    RouteAction = iota // Block the request (fail it)
	RouteContinue                    // Let it continue (optionally modified)
)

type ScreenshotOptions

type ScreenshotOptions struct {
	FullPage  bool // capture the entire scrollable page
	Quality   int  // JPEG quality (1-100), 0 means PNG format
	ElementID int  // if > 0, capture only this element
}

ScreenshotOptions controls the screenshot behavior.

type SnapshotOptions

type SnapshotOptions struct {
	EnableOCR       bool
	OCRLanguages    []string
	OCRDebugDir     string
	InteractiveOnly bool   // only show interactive elements (3.8)
	Compact         bool   // compact mode: omit unnamed structural wrappers (3.9)
	MaxDepth        int    // 0 = unlimited (3.10)
	Cursor          bool   // show cursor position in snapshot
	Selector        string // CSS selector to scope the snapshot to a subtree
}

type SnapshotResult

type SnapshotResult struct {
	Text     string
	Nodes    []*axtree.Node
	IDMap    map[int]int64
	RawCount int
}

type TabInfo

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

TabInfo represents information about a single browser tab.

Jump to

Keyboard shortcuts

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