bonk

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2026 License: MIT Imports: 26 Imported by: 0

README

bonk

Go Reference Go Report Card

A fast, stealth-first browser automation library for Go. Direct Chrome DevTools Protocol over WebSocket — no WebDriver, no relay, no detection.

Documentation

Features

  • Direct CDP — WebSocket to Chrome, zero intermediaries, undetectable by default
  • Stealth by default — skips Runtime.enable, patches navigator/plugins/WebGL, strips headless signals
  • Code-generated protocol bindings — full coverage of all 55 CDP domains from upstream .pdl files
  • Context-awarepage.WithContext(ctx) / page.Timeout(d) for deadlines and cancellation
  • Auto-wait elements — polls for visibility before interaction, retries stale references
  • Network interception — intercept, modify, mock, or block requests and responses via the Fetch domain
  • Device emulation — built-in presets for iPhone 15, Pixel 8, iPad Pro, Galaxy S23, and more
  • Session persistence — save and restore cookies and localStorage across runs
  • Isolated contexts — separate cookie jars, proxies, viewports, and locales per context
  • Single dependency — only coder/websocket

Installation

go get github.com/joakimcarlsson/bonk

Quick Start

package main

import (
	"fmt"
	"log"

	"github.com/joakimcarlsson/bonk"
)

func main() {
	b, err := bonk.Launch()
	if err != nil {
		log.Fatal(err)
	}
	defer b.Close()

	ctx, err := b.NewContext()
	if err != nil {
		log.Fatal(err)
	}

	page, err := ctx.NewPage()
	if err != nil {
		log.Fatal(err)
	}

	if err := page.Navigate("https://example.com"); err != nil {
		log.Fatal(err)
	}

	title, _ := page.Title()
	fmt.Println(title)
}

License

See LICENSE file.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	IPhone15 = Device{
		Name:              "iPhone 15",
		UserAgent:         "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1",
		ViewportWidth:     393,
		ViewportHeight:    852,
		DeviceScaleFactor: 3,
		IsMobile:          true,
		HasTouch:          true,
	}

	IPhone15ProMax = Device{
		Name:              "iPhone 15 Pro Max",
		UserAgent:         "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1",
		ViewportWidth:     430,
		ViewportHeight:    932,
		DeviceScaleFactor: 3,
		IsMobile:          true,
		HasTouch:          true,
	}

	Pixel7 = Device{
		Name:              "Pixel 7",
		UserAgent:         "Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36",
		ViewportWidth:     412,
		ViewportHeight:    915,
		DeviceScaleFactor: 2.625,
		IsMobile:          true,
		HasTouch:          true,
	}

	Pixel8 = Device{
		Name:              "Pixel 8",
		UserAgent:         "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Mobile Safari/537.36",
		ViewportWidth:     412,
		ViewportHeight:    915,
		DeviceScaleFactor: 2.625,
		IsMobile:          true,
		HasTouch:          true,
	}

	IPadPro11 = Device{
		Name:              "iPad Pro 11",
		UserAgent:         "Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1",
		ViewportWidth:     834,
		ViewportHeight:    1194,
		DeviceScaleFactor: 2,
		IsMobile:          true,
		HasTouch:          true,
	}

	IPadAir = Device{
		Name:              "iPad Air",
		UserAgent:         "Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1",
		ViewportWidth:     820,
		ViewportHeight:    1180,
		DeviceScaleFactor: 2,
		IsMobile:          true,
		HasTouch:          true,
	}

	GalaxyS23 = Device{
		Name:              "Galaxy S23",
		UserAgent:         "Mozilla/5.0 (Linux; Android 13; SM-S911B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36",
		ViewportWidth:     360,
		ViewportHeight:    780,
		DeviceScaleFactor: 3,
		IsMobile:          true,
		HasTouch:          true,
	}
)
View Source
var (
	ErrBrowserClosed  = errors.New("bonk: browser closed")
	ErrContextClosed  = errors.New("bonk: context closed")
	ErrPageClosed     = errors.New("bonk: page closed")
	ErrSessionClosed  = errors.New("bonk: session closed")
	ErrChromeNotFound = errors.New("bonk: chrome binary not found")
	ErrChromeStartup  = errors.New("bonk: chrome failed to start")
	ErrStaleElement   = errors.New("bonk: stale element reference")
)

Functions

func FormatAccessibilityTree added in v0.2.0

func FormatAccessibilityTree(nodes []*AXNode) string

FormatAccessibilityTree formats the tree as indexed text for LLM consumption. Interactive elements get numbered indices; non-interactive elements are shown without indices.

Types

type AXNode added in v0.2.0

type AXNode struct {
	Role     string
	Name     string
	Value    string
	Disabled bool
	Focused  bool
	Checked  string
	Selected bool
	Expanded string
	Level    int
	Children []*AXNode
}

AXNode represents a node in the accessibility tree.

type Box

type Box struct {
	X      float64
	Y      float64
	Width  float64
	Height float64
}

BoundingBox returns the element's bounding rectangle.

type Browser

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

Browser represents a running Chrome instance.

func Connect

func Connect(wsURL string, opts ...LaunchOption) (*Browser, error)

Connect attaches to an already-running Chrome instance.

func Launch

func Launch(opts ...LaunchOption) (*Browser, error)

Launch starts a new Chrome browser process and connects to it.

func (*Browser) Close

func (b *Browser) Close() error

Close shuts down the browser and cleans up resources.

func (*Browser) NewContext

func (b *Browser) NewContext(opts ...ContextOption) (*BrowserContext, error)

NewContext creates a new isolated browser context.

func (*Browser) OnDisconnect

func (b *Browser) OnDisconnect(fn func())

OnDisconnect registers a callback invoked when the WebSocket connection drops.

func (*Browser) Reconnect

func (b *Browser) Reconnect() error

Reconnect re-establishes the WebSocket connection to the browser. Useful after the connection drops unexpectedly.

type BrowserContext

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

BrowserContext represents an isolated browser context with its own cookies, cache, and storage.

func (*BrowserContext) Browser

func (c *BrowserContext) Browser() *Browser

Browser returns the parent browser.

func (*BrowserContext) ClearCookies

func (c *BrowserContext) ClearCookies() error

ClearCookies clears all cookies in the browser context.

func (*BrowserContext) Close

func (c *BrowserContext) Close() error

Close disposes the browser context and all its pages.

func (*BrowserContext) Cookies

func (c *BrowserContext) Cookies() ([]Cookie, error)

Cookies returns all cookies in the browser context. Requires at least one page to be open.

func (*BrowserContext) LoadState

func (c *BrowserContext) LoadState(path string) error

LoadState restores browser context state from a file.

func (*BrowserContext) NewPage

func (c *BrowserContext) NewPage() (*Page, error)

NewPage creates a new page (tab) in this browser context.

func (*BrowserContext) Pages

func (c *BrowserContext) Pages() []*Page

Pages returns all open pages in this context.

func (*BrowserContext) SaveState

func (c *BrowserContext) SaveState(path string) error

SaveState saves the browser context state (cookies, localStorage) to a file.

func (*BrowserContext) SetCookies

func (c *BrowserContext) SetCookies(cookies ...Cookie) error

SetCookies sets cookies in the browser context.

type BrowserState

type BrowserState struct {
	Cookies      []Cookie                     `json:"cookies"`
	LocalStorage map[string]map[string]string `json:"localStorage,omitempty"`
}

BrowserState holds serializable browser state for persistence. Includes cookies and localStorage. IndexedDB is not supported.

type ConsoleMessage

type ConsoleMessage struct {
	Type string
	Text string
	Args []any
}

ConsoleMessage represents a console API call.

type ContextOption

type ContextOption func(*contextConfig)

ContextOption configures a browser context.

func WithGeolocation

func WithGeolocation(lat, lon float64) ContextOption

WithGeolocation sets the geolocation override.

func WithLocale

func WithLocale(locale string) ContextOption

WithLocale sets the browser locale.

func WithProxy

func WithProxy(server string) ContextOption

WithProxy sets a proxy server for the context.

func WithProxyBypass

func WithProxyBypass(list string) ContextOption

WithProxyBypass sets the proxy bypass list.

func WithState

func WithState(path string) ContextOption

WithState loads browser state (cookies, localStorage) from a file.

func WithTimezone

func WithTimezone(tz string) ContextOption

WithTimezone sets the timezone override.

func WithUserAgent

func WithUserAgent(ua string) ContextOption

WithUserAgent sets the user agent string for the context.

func WithViewport

func WithViewport(width, height int) ContextOption

WithViewport sets the default viewport size for new pages.

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

Cookie represents a browser cookie.

type Device

type Device struct {
	Name              string
	UserAgent         string
	ViewportWidth     int
	ViewportHeight    int
	DeviceScaleFactor float64
	IsMobile          bool
	HasTouch          bool
}

Device describes a device profile for emulation.

type Dialog

type Dialog struct {
	Type          string
	Message       string
	DefaultPrompt string
	// contains filtered or unexported fields
}

Dialog represents a JavaScript dialog (alert, confirm, prompt).

func (*Dialog) Accept

func (d *Dialog) Accept(text ...string) error

Accept accepts the dialog, optionally providing text for prompts.

func (*Dialog) Dismiss

func (d *Dialog) Dismiss() error

Dismiss dismisses the dialog.

type Download

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

Download represents a file download.

func (*Download) SaveAs

func (d *Download) SaveAs(path string) error

SaveAs copies the downloaded file to the given path. Blocks until the download completes.

func (*Download) SaveAsContext

func (d *Download) SaveAsContext(ctx context.Context, path string) error

SaveAsContext copies the downloaded file to the given path, respecting the context for cancellation and deadlines.

func (*Download) SuggestedFilename

func (d *Download) SuggestedFilename() string

SuggestedFilename returns the browser-suggested filename.

func (*Download) URL

func (d *Download) URL() string

URL returns the download URL.

type Element

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

Element represents a DOM element on a page.

func (*Element) Attribute

func (e *Element) Attribute(name string) (string, error)

Attribute returns the value of the named attribute.

func (*Element) BoundingBox

func (e *Element) BoundingBox() (*Box, error)

BoundingBox returns the element's bounding box in viewport coordinates.

func (*Element) Check

func (e *Element) Check() error

Check checks a checkbox or radio button if not already checked.

func (*Element) Click

func (e *Element) Click() error

Click scrolls the element into view and clicks it.

func (*Element) DoubleClick

func (e *Element) DoubleClick() error

DoubleClick scrolls the element into view and double-clicks it.

func (*Element) Fill

func (e *Element) Fill(text string) error

Fill clears the input field and inserts the given text.

func (*Element) Focus

func (e *Element) Focus() error

Focus focuses the element.

func (*Element) HTML

func (e *Element) HTML() (string, error)

HTML returns the outer HTML of the element.

func (*Element) Hover

func (e *Element) Hover() error

Hover scrolls the element into view and moves the mouse to it.

func (*Element) InnerText

func (e *Element) InnerText() (string, error)

InnerText returns the rendered text content of the element.

func (*Element) IsVisible

func (e *Element) IsVisible() (bool, error)

IsVisible reports whether the element is visible.

func (*Element) Press

func (e *Element) Press(key string) error

Press sends a single key press event.

func (*Element) Screenshot

func (e *Element) Screenshot(path string, opts ...ScreenshotOption) error

Screenshot captures a screenshot of the element and saves it to the given path.

func (*Element) ScreenshotBytes added in v0.2.0

func (e *Element) ScreenshotBytes(
	opts ...ScreenshotOption,
) ([]byte, error)

ScreenshotBytes captures a screenshot of the element and returns PNG bytes.

func (*Element) ScrollIntoView

func (e *Element) ScrollIntoView() error

ScrollIntoView scrolls the element into view.

func (*Element) SelectOption

func (e *Element) SelectOption(value string) error

SelectOption selects an option in a <select> element by value.

func (*Element) Text

func (e *Element) Text() (string, error)

Text returns the text content of the element.

func (*Element) Type

func (e *Element) Type(text string, opts ...TypeOption) error

Type types the given text character by character with key events.

func (*Element) Uncheck

func (e *Element) Uncheck() error

Uncheck unchecks a checkbox if currently checked.

func (*Element) Upload

func (e *Element) Upload(paths ...string) error

Upload sets files on a file input element.

func (*Element) WaitForHidden

func (e *Element) WaitForHidden(opts ...WaitOption) error

WaitForHidden waits until the element becomes hidden.

func (*Element) WaitForVisible

func (e *Element) WaitForVisible(opts ...WaitOption) error

WaitForVisible waits until the element becomes visible.

type ElementNotFoundError

type ElementNotFoundError struct {
	Selector string
}

ElementNotFoundError is returned when a selector matches no elements.

func (*ElementNotFoundError) Error

func (e *ElementNotFoundError) Error() string

type EventType

type EventType string

EventType identifies a page event.

const (
	ConsoleEvent  EventType = "console"
	DialogEvent   EventType = "dialog"
	DownloadEvent EventType = "download"
)

type Frame

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

Frame represents an iframe within a page.

func (*Frame) Click

func (f *Frame) Click(selector string, opts ...WaitOption) error

Click waits for the selector in this frame and clicks the element.

func (*Frame) Evaluate

func (f *Frame) Evaluate(expression string) (any, error)

Evaluate executes JavaScript in this frame's context.

func (*Frame) Fill

func (f *Frame) Fill(selector, text string, opts ...WaitOption) error

Fill waits for the selector in this frame and fills the input.

func (*Frame) GetByAltText added in v0.2.0

func (f *Frame) GetByAltText(text string, opts ...TextMatchOption) *Locator

GetByAltText returns a Locator matching elements by their alt attribute within the frame.

func (*Frame) GetByLabel added in v0.2.0

func (f *Frame) GetByLabel(text string, opts ...TextMatchOption) *Locator

GetByLabel returns a Locator matching form controls by their associated label text within the frame.

func (*Frame) GetByPlaceholder added in v0.2.0

func (f *Frame) GetByPlaceholder(
	text string,
	opts ...TextMatchOption,
) *Locator

GetByPlaceholder returns a Locator matching elements by their placeholder attribute within the frame.

func (*Frame) GetByRole added in v0.2.0

func (f *Frame) GetByRole(role string, opts ...GetByRoleOption) *Locator

GetByRole returns a Locator matching elements by ARIA role within the frame.

func (*Frame) GetByTestId added in v0.2.0

func (f *Frame) GetByTestId(id string) *Locator

GetByTestId returns a Locator matching elements by their data-testid attribute within the frame.

func (*Frame) GetByText added in v0.2.0

func (f *Frame) GetByText(text string, opts ...TextMatchOption) *Locator

GetByText returns a Locator matching elements by their visible text content within the frame.

func (*Frame) GetByTitle added in v0.2.0

func (f *Frame) GetByTitle(text string, opts ...TextMatchOption) *Locator

GetByTitle returns a Locator matching elements by their title attribute within the frame.

func (*Frame) ID

func (f *Frame) ID() proto.FrameID

ID returns the frame's unique identifier.

func (*Frame) Locator

func (f *Frame) Locator(selector string) *Locator

Locator returns a Locator for the given CSS selector within the frame.

func (*Frame) Name

func (f *Frame) Name() string

Name returns the frame's name attribute.

func (*Frame) Query

func (f *Frame) Query(selector string) (*Element, error)

Query finds the first element matching the CSS selector within this frame.

func (*Frame) QueryAll

func (f *Frame) QueryAll(selector string) ([]*Element, error)

QueryAll finds all elements matching the CSS selector within this frame.

func (*Frame) URL

func (f *Frame) URL() string

URL returns the frame's document URL.

func (*Frame) WaitSelector

func (f *Frame) WaitSelector(
	selector string,
	opts ...WaitOption,
) (*Element, error)

WaitSelector waits for an element matching the selector within this frame.

type GetByRoleOption added in v0.2.0

type GetByRoleOption func(*getByRoleConfig)

GetByRoleOption configures GetByRole behavior.

func WithName added in v0.2.0

func WithName(name string, opts ...TextMatchOption) GetByRoleOption

WithName filters elements by their accessible name. Pass Exact() to require an exact name match.

type Keyboard

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

Keyboard provides low-level keyboard control on a page.

func (*Keyboard) Down

func (k *Keyboard) Down(key string) error

Down sends a key down event.

func (*Keyboard) InsertText

func (k *Keyboard) InsertText(text string) error

InsertText inserts text without key events (instant).

func (*Keyboard) Press

func (k *Keyboard) Press(key string) error

Press sends a key down followed by key up event.

func (*Keyboard) Type

func (k *Keyboard) Type(text string, opts ...TypeOption) error

Type types text character by character with key events.

func (*Keyboard) Up

func (k *Keyboard) Up(key string) error

Up sends a key up event.

type LaunchOption

type LaunchOption func(*launchConfig)

LaunchOption configures browser launch behavior.

func Args

func Args(args ...string) LaunchOption

Args appends additional command-line arguments to the Chrome launch.

func ChromePath

func ChromePath(path string) LaunchOption

ChromePath sets an explicit path to the Chrome binary.

func Env

func Env(env ...string) LaunchOption

Env appends additional environment variables for the Chrome process.

func Headless

func Headless(v bool) LaunchOption

Headless controls whether Chrome runs in headless mode. Default is true.

func Stealth

func Stealth(v bool) LaunchOption

Stealth enables anti-detection measures. Default is true. When enabled: disables automation-revealing Chrome flags, skips Runtime.enable (which is the primary CDP detection signal), injects JS patches to spoof navigator properties, and ensures Client Hints headers are consistent. Trade-off: OnConsole event handler won't work in stealth mode.

func UserDataDir

func UserDataDir(path string) LaunchOption

UserDataDir sets the user data directory for Chrome. If empty, a temporary directory is created and cleaned up on Close.

func WithLogger

func WithLogger(l *slog.Logger) LaunchOption

WithLogger enables debug logging of all CDP messages using the given logger.

type Locator

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

Locator is a Playwright-style selector handle that re-queries on every action. Locators never go stale because they don't cache a DOM reference.

func (*Locator) And added in v0.2.0

func (l *Locator) And(other *Locator) *Locator

And returns a new Locator matching elements that satisfy both this locator and the other locator.

func (*Locator) Attribute

func (l *Locator) Attribute(name string) (string, error)

Attribute returns the value of the named attribute.

func (*Locator) BoundingBox

func (l *Locator) BoundingBox() (*Box, error)

BoundingBox returns the element's bounding box.

func (*Locator) Click

func (l *Locator) Click(opts ...WaitOption) error

Click waits for the element and clicks it.

func (*Locator) Count

func (l *Locator) Count() (int, error)

Count returns the number of elements matching the selector.

func (*Locator) Fill

func (l *Locator) Fill(text string, opts ...WaitOption) error

Fill waits for the element and fills it with text.

func (*Locator) Filter added in v0.2.0

func (l *Locator) Filter(f LocatorFilter) *Locator

Filter returns a new Locator that narrows matches by the given criteria. All specified criteria must be satisfied (AND semantics).

func (*Locator) First

func (l *Locator) First() *Locator

First returns a Locator that resolves to the first match.

func (*Locator) HTML

func (l *Locator) HTML() (string, error)

HTML returns the outer HTML of the element.

func (*Locator) InnerText

func (l *Locator) InnerText() (string, error)

InnerText returns the rendered text content of the element.

func (*Locator) IsVisible

func (l *Locator) IsVisible() (bool, error)

IsVisible reports whether the element is visible.

func (*Locator) Nth

func (l *Locator) Nth(n int) *Locator

Nth returns a Locator that resolves to the nth match (zero-based).

func (*Locator) Or added in v0.2.0

func (l *Locator) Or(other *Locator) *Locator

Or returns a new Locator matching elements that satisfy either this locator or the other locator. Results are in document order.

func (*Locator) Press

func (l *Locator) Press(key string, opts ...WaitOption) error

Press waits for the element and presses a key.

func (*Locator) Screenshot

func (l *Locator) Screenshot(path string, opts ...ScreenshotOption) error

Screenshot captures a screenshot of the element.

func (*Locator) Text

func (l *Locator) Text() (string, error)

Text returns the text content of the element.

func (*Locator) Type

func (l *Locator) Type(text string, opts ...TypeOption) error

Type waits for the element and types text character by character.

func (*Locator) WaitFor

func (l *Locator) WaitFor(opts ...WaitOption) error

WaitFor waits until the element is attached to the DOM.

type LocatorFilter added in v0.2.0

type LocatorFilter struct {
	HasText    string
	HasNotText string
	Has        *Locator
	HasNot     *Locator
}

LocatorFilter specifies criteria for narrowing locator matches.

type Mouse

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

Mouse provides low-level mouse control on a page.

func (*Mouse) Click

func (m *Mouse) Click(x, y float64) error

Click moves to the coordinates and performs a click.

func (*Mouse) Down

func (m *Mouse) Down() error

Down presses the left mouse button at the current position.

func (*Mouse) DragTo

func (m *Mouse) DragTo(fromX, fromY, toX, toY float64) error

DragTo performs a drag from one point to another.

func (*Mouse) Move

func (m *Mouse) Move(x, y float64) error

Move moves the mouse to the given coordinates.

func (*Mouse) Up

func (m *Mouse) Up() error

Up releases the left mouse button at the current position.

type NavigateOption func(*navigateConfig)

NavigateOption configures navigation behavior.

func WithTimeout

func WithTimeout(d time.Duration) NavigateOption

WithTimeout sets the navigation timeout.

func WithWaitUntil

func WithWaitUntil(w NavigateWait) NavigateOption

WithWaitUntil sets when navigation is considered complete.

type NavigateWait int

NavigateWait specifies when navigation is considered complete.

const (
	WaitLoad NavigateWait = iota
	WaitDOMContentLoaded
	WaitNetworkIdle
)
type NavigationError struct {
	URL     string
	Message string
	Cause   error
}

NavigationError is returned when page navigation fails.

func (e *NavigationError) Error() string
func (e *NavigationError) Unwrap() error

Unwrap returns the underlying cause.

type Page

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

Page represents a single browser tab/page.

func (*Page) AccessibilityTree added in v0.2.0

func (p *Page) AccessibilityTree() ([]*AXNode, error)

AccessibilityTree returns the page's accessibility tree.

func (*Page) AddInitScript

func (p *Page) AddInitScript(script string) error

AddInitScript adds a script that will be evaluated on every new document created in the page, including iframes. Useful for injecting polyfills or overriding APIs before page scripts run.

func (*Page) BringToFront

func (p *Page) BringToFront() error

BringToFront activates this page (tab).

func (*Page) Click

func (p *Page) Click(selector string, opts ...WaitOption) error

Click waits for the selector and clicks the element.

func (*Page) Close

func (p *Page) Close() error

Close closes the page.

func (*Page) Content

func (p *Page) Content() (string, error)

Content returns the full HTML content of the page.

func (*Page) Context

func (p *Page) Context() *BrowserContext

Context returns the parent browser context.

func (*Page) Emulate

func (p *Page) Emulate(d Device) error

Emulate applies a device profile to the page, setting viewport, user agent, device scale factor, and touch emulation.

func (*Page) Evaluate

func (p *Page) Evaluate(expression string) (any, error)

Evaluate executes a JavaScript expression and returns the result as a Go value.

func (*Page) EvaluateHandle

func (p *Page) EvaluateHandle(expression string) (*Element, error)

EvaluateHandle executes a JavaScript expression and returns the result as an Element handle (for non-primitive return values like DOM nodes).

func (*Page) EvaluateOn

func (p *Page) EvaluateOn(el *Element, fn string, args ...any) (any, error)

EvaluateOn executes a JavaScript function with the element as `this`. The function should be in the form "function(arg1, arg2) { ... }".

func (*Page) ExposeFunction

func (p *Page) ExposeFunction(
	name string,
	fn func(args []json.RawMessage) (any, error),
) (func(), error)

ExposeFunction exposes a Go function to page JavaScript under the given name. The function receives a slice of arguments and returns a value or error. Page scripts can call the function as `window.<name>(args...)`.

func (*Page) Fill

func (p *Page) Fill(selector, text string, opts ...WaitOption) error

Fill waits for the selector and fills the input with text.

func (*Page) Frame

func (p *Page) Frame(nameOrID string) (*Frame, error)

Frame finds a frame by name or ID.

func (*Page) Frames

func (p *Page) Frames() ([]*Frame, error)

Frames returns all frames in the page's frame tree.

func (*Page) GetByAltText added in v0.2.0

func (p *Page) GetByAltText(text string, opts ...TextMatchOption) *Locator

GetByAltText returns a Locator matching elements by their alt attribute.

func (*Page) GetByLabel added in v0.2.0

func (p *Page) GetByLabel(text string, opts ...TextMatchOption) *Locator

GetByLabel returns a Locator matching form controls by their associated label text. Checks <label> elements, aria-label, and aria-labelledby attributes.

func (*Page) GetByPlaceholder added in v0.2.0

func (p *Page) GetByPlaceholder(text string, opts ...TextMatchOption) *Locator

GetByPlaceholder returns a Locator matching elements by their placeholder attribute.

func (*Page) GetByRole added in v0.2.0

func (p *Page) GetByRole(role string, opts ...GetByRoleOption) *Locator

GetByRole returns a Locator matching elements by ARIA role. Matches both explicit role attributes and implicit roles from HTML semantics.

func (*Page) GetByTestId added in v0.2.0

func (p *Page) GetByTestId(id string) *Locator

GetByTestId returns a Locator matching elements by their data-testid attribute.

func (*Page) GetByText added in v0.2.0

func (p *Page) GetByText(text string, opts ...TextMatchOption) *Locator

GetByText returns a Locator matching elements by their visible text content.

func (*Page) GetByTitle added in v0.2.0

func (p *Page) GetByTitle(text string, opts ...TextMatchOption) *Locator

GetByTitle returns a Locator matching elements by their title attribute.

func (*Page) GoBack

func (p *Page) GoBack(opts ...NavigateOption) error

GoBack navigates back in history and waits for completion.

func (*Page) GoForward

func (p *Page) GoForward(opts ...NavigateOption) error

GoForward navigates forward in history and waits for completion.

func (*Page) IsClosed

func (p *Page) IsClosed() bool

IsClosed reports whether the page has been closed.

func (*Page) Keyboard

func (p *Page) Keyboard() *Keyboard

Keyboard returns the page's Keyboard controller.

func (*Page) Locator

func (p *Page) Locator(selector string) *Locator

Locator returns a Locator for the given CSS selector on the page.

func (*Page) Mouse

func (p *Page) Mouse() *Mouse

Mouse returns the page's Mouse controller.

func (*Page) Navigate

func (p *Page) Navigate(url string, opts ...NavigateOption) error

Navigate navigates the page to the given URL and waits for completion.

func (*Page) On

func (p *Page) On(event EventType, handler any) func()

On registers a typed event handler. The handler type must match the event:

  • Console → func(*ConsoleMessage)
  • Dialog → func(*Dialog)
  • Download → func(*Download)

func (*Page) OnConsole

func (p *Page) OnConsole(fn func(*ConsoleMessage)) func()

OnConsole registers a handler for console messages.

func (*Page) OnDialog

func (p *Page) OnDialog(fn func(*Dialog)) func()

OnDialog registers a handler for JavaScript dialogs.

func (*Page) OnRequest

func (p *Page) OnRequest(fn func(*Request)) func()

OnRequest registers a handler for intercepted requests. The handler can observe, modify headers, abort, or fulfill the request. If the handler doesn't call Continue, Abort, or Fulfill, the request is automatically continued.

func (*Page) OnResponse

func (p *Page) OnResponse(fn func(*Response)) func()

OnResponse registers a handler for intercepted responses. The handler can read the response body before it reaches the page. If the handler doesn't call Continue, the response is automatically continued.

func (*Page) PDF

func (p *Page) PDF(path string) error

PDF saves the page as a PDF file.

func (*Page) PDFBytes added in v0.2.0

func (p *Page) PDFBytes() ([]byte, error)

PDFBytes renders the page as a PDF and returns the raw bytes.

func (*Page) Press

func (p *Page) Press(selector, key string, opts ...WaitOption) error

Press waits for the selector and presses a key.

func (*Page) Query

func (p *Page) Query(selector string) (*Element, error)

Query finds the first element matching the CSS selector. Returns nil if no element matches.

func (*Page) QueryAll

func (p *Page) QueryAll(selector string) ([]*Element, error)

QueryAll finds all elements matching the CSS selector.

func (*Page) Reload

func (p *Page) Reload(opts ...NavigateOption) error

Reload reloads the current page and waits for completion.

func (*Page) Route

func (p *Page) Route(pattern string, handler func(*Route)) func()

Route intercepts requests matching the URL pattern. The handler receives a Route that can be fulfilled, continued, or aborted.

func (*Page) Screenshot

func (p *Page) Screenshot(path string, opts ...ScreenshotOption) error

Screenshot captures a screenshot and saves it to the given path.

func (*Page) ScreenshotBytes added in v0.2.0

func (p *Page) ScreenshotBytes(
	opts ...ScreenshotOption,
) ([]byte, error)

ScreenshotBytes captures a screenshot and returns it as image bytes. Defaults to PNG unless AsJPEG is specified.

func (*Page) SetContent

func (p *Page) SetContent(html string) error

SetContent replaces the page's document HTML.

func (*Page) SetExtraHTTPHeaders

func (p *Page) SetExtraHTTPHeaders(headers map[string]string) error

SetExtraHTTPHeaders sets headers that will be sent with every request.

func (*Page) SetOffline

func (p *Page) SetOffline(offline bool) error

SetOffline enables or disables offline emulation.

func (*Page) SetViewport

func (p *Page) SetViewport(width, height int) error

SetViewport sets the page viewport dimensions.

func (*Page) Timeout

func (p *Page) Timeout(d time.Duration) *Page

Timeout returns a shallow copy of the Page with a context deadline set to the given duration from now.

func (*Page) Title

func (p *Page) Title() (string, error)

Title returns the current page title.

func (*Page) Type

func (p *Page) Type(
	selector, text string,
	opts ...TypeOption,
) error

Type waits for the selector and types text character by character.

func (*Page) URL

func (p *Page) URL() (string, error)

URL returns the current page URL.

func (*Page) WaitForFunction

func (p *Page) WaitForFunction(expression string, opts ...WaitOption) error

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

func (*Page) WaitForPopup added in v0.2.0

func (p *Page) WaitForPopup(opts ...PopupOption) (*Page, error)

WaitForPopup waits for a new page (tab/popup) to be opened by this page and returns it. The caller should trigger the popup after calling this method.

func (*Page) WaitForURL

func (p *Page) WaitForURL(pattern string, opts ...WaitOption) error

WaitForURL waits until the page URL matches the given glob pattern.

func (*Page) WaitNavigation

func (p *Page) WaitNavigation(opts ...NavigateOption) error

WaitNavigation waits for the next navigation to complete.

func (*Page) WaitSelector

func (p *Page) WaitSelector(
	selector string,
	opts ...WaitOption,
) (*Element, error)

WaitSelector waits for an element matching the selector to appear. By default waits for the element to be attached to the DOM. Use WaitVisibleOption() to also require visibility, or WaitHiddenOption() to wait until the element is hidden or removed.

func (*Page) WithContext

func (p *Page) WithContext(ctx context.Context) *Page

WithContext returns a shallow copy of the Page with the given context. All CDP calls made on the returned Page will respect the context's deadline and cancellation. The copy shares the underlying session, fetch manager, and mutex with the original.

type Pool

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

Pool manages a pool of reusable pages for concurrent automation.

func NewPool

func NewPool(ctx *BrowserContext, size int) (*Pool, error)

NewPool creates a pool of the given size, pre-creating pages.

func (*Pool) Close

func (p *Pool) Close()

Close closes all pages in the pool.

func (*Pool) Do

func (p *Pool) Do(fn func(*Page) error) error

Do checks out a page, runs fn, and returns it to the pool. Blocks if all pages are in use.

type PopupOption added in v0.2.0

type PopupOption func(*popupConfig)

PopupOption configures WaitForPopup behavior.

func PopupTimeout added in v0.2.0

func PopupTimeout(d time.Duration) PopupOption

PopupTimeout sets the maximum time to wait for a popup.

type Request

type Request struct {
	URL          string
	Method       string
	Headers      map[string]string
	PostData     string
	ResourceType string
	// contains filtered or unexported fields
}

Request represents an intercepted network request. Call Continue, Abort, or Fulfill to handle the request.

func (*Request) Abort

func (r *Request) Abort() error

Abort blocks the request.

func (*Request) Continue

func (r *Request) Continue() error

Continue allows the request to proceed, applying any modified headers.

func (*Request) Fulfill

func (r *Request) Fulfill(
	status int,
	headers map[string]string,
	body string,
) error

Fulfill responds to the request with a custom response.

func (*Request) SetHeader

func (r *Request) SetHeader(key, value string)

SetHeader sets or overrides a request header. The modified header is applied when Continue is called.

type Response

type Response struct {
	URL     string
	Status  int64
	Headers map[string]string
	// contains filtered or unexported fields
}

Response represents an intercepted network response.

func (*Response) Body

func (r *Response) Body() ([]byte, error)

Body returns the response body bytes.

func (*Response) Continue

func (r *Response) Continue() error

Continue allows the response to proceed to the page.

type Route

type Route struct {
	Request *Request
	// contains filtered or unexported fields
}

Route represents a pattern-matched intercepted request.

func (*Route) Abort

func (r *Route) Abort() error

Abort blocks the request.

func (*Route) Continue

func (r *Route) Continue() error

Continue allows the request to proceed.

func (*Route) Fulfill

func (r *Route) Fulfill(
	status int,
	headers map[string]string,
	body string,
) error

Fulfill responds to the request with a custom response.

type ScreenshotOption

type ScreenshotOption func(*screenshotConfig)

ScreenshotOption configures screenshot behavior.

func AsJPEG added in v0.2.0

func AsJPEG() ScreenshotOption

AsJPEG captures the screenshot as JPEG instead of PNG. Quality defaults to 80 if not set via ScreenshotQuality.

func FullPage

func FullPage() ScreenshotOption

FullPage captures the full scrollable page.

func MaxWidth added in v0.2.0

func MaxWidth(px int) ScreenshotOption

MaxWidth sets the maximum width for the screenshot. If the captured image is wider, it is downscaled proportionally.

func ScreenshotQuality

func ScreenshotQuality(q int) ScreenshotOption

ScreenshotQuality sets the JPEG/WebP quality (0-100).

type TextMatchOption added in v0.2.0

type TextMatchOption func(*textMatchConfig)

TextMatchOption configures text matching behavior for GetBy* methods.

func Exact added in v0.2.0

func Exact() TextMatchOption

Exact requires an exact text match instead of substring containment.

type TimeoutError

type TimeoutError struct {
	Operation string
	Selector  string
	Cause     error
}

TimeoutError is returned when an operation exceeds its deadline.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

Unwrap returns the underlying cause.

type TypeOption

type TypeOption func(*typeConfig)

TypeOption configures typing behavior.

func WaitFor

func WaitFor(opts ...WaitOption) TypeOption

WaitFor adds wait options that apply when page.Type() waits for the selector.

func WithDelay

func WithDelay(d time.Duration) TypeOption

WithDelay sets the delay between keystrokes.

type WaitOption

type WaitOption func(*waitConfig)

WaitOption configures wait behavior.

func WaitHiddenOption

func WaitHiddenOption() WaitOption

WaitHiddenOption sets WaitSelector to wait until the element is hidden or removed.

func WaitInterval

func WaitInterval(d time.Duration) WaitOption

WaitInterval sets the initial polling interval.

func WaitTimeout

func WaitTimeout(d time.Duration) WaitOption

WaitTimeout sets the maximum time to wait.

func WaitVisibleOption

func WaitVisibleOption() WaitOption

WaitVisibleOption sets the visibility condition for WaitSelector.

type WaitVisibility

type WaitVisibility int

WaitVisibility specifies what state to wait for.

const (
	WaitAttached WaitVisibility = iota
	WaitUntilVisible
	WaitUntilHidden
)

Directories

Path Synopsis
cmd
bonkmcp command
examples
basic command
interact command
network command
internal
cmd/bonkgen command
gen
pdl

Jump to

Keyboard shortcuts

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