browser

package
v0.2.19 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 34 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 owns the Chromium lifecycle and page navigation. The terminal renderer is deliberately separate: termcast consumes the chromedp context, while this package stays usable by a future TUI or automation tool.

Index

Constants

This section is empty.

Variables

View Source
var ErrLastTab = errors.New("cannot close the final tab")

ErrLastTab is returned when closing a tab would leave no user-visible tab.

View Source
var ErrNoHistory = errors.New("no history entry")

ErrNoHistory means Back/Forward had nowhere to go.

View Source
var ErrTabsClosed = errors.New("tabs are closed")

ErrTabsClosed is returned by operations on a closed Tabs collection.

Functions

func DefaultProfileDir added in v0.2.0

func DefaultProfileDir() (string, error)

DefaultProfileDir returns kitty-browse's default, independent Chromium profile. It never points at or copies a user's regular Chrome profile.

func HintLabels

func HintLabels(n int) []string

HintLabels returns at most n labels: first the home-row keys, then pairs.

func Normalize

func Normalize(raw string) (string, error)

Normalize adds https:// to a bare host and accepts http, https, file, and exactly about:blank. Other about URLs remain unsupported.

func PruneStalePrivateProfiles added in v0.2.1

func PruneStalePrivateProfiles(now time.Time)

PruneStalePrivateProfiles removes private Chromium profiles left behind when a previous kitty-browse process was killed before it could cancel its allocator. A profile is kept while the recorded owner PID is alive.

Types

type AutomationError added in v0.2.0

type AutomationError struct{ Code, Message string }

func (*AutomationError) Error added in v0.2.0

func (e *AutomationError) Error() string

func (*AutomationError) ErrorCode added in v0.2.0

func (e *AutomationError) ErrorCode() string

type DialogStatus added in v0.2.0

type DialogStatus struct {
	Open          bool   `json:"open"`
	Type          string `json:"type"`
	Message       string `json:"message"`
	DefaultPrompt string `json:"defaultPrompt"`
}

DialogStatus is a deliberately small projection of the current JavaScript dialog. Prompt input and the result of a closed dialog are never retained.

type Download added in v0.2.0

type Download struct {
	GUID              string  `json:"guid"`
	URL               string  `json:"url,omitempty"`
	SuggestedFilename string  `json:"suggestedFilename,omitempty"`
	State             string  `json:"state"`
	ReceivedBytes     float64 `json:"receivedBytes"`
	TotalBytes        float64 `json:"totalBytes"`
	Path              string  `json:"path,omitempty"`
	Scope             string  `json:"scope"`
	// contains filtered or unexported fields
}

Download is a metadata-only, browser-scoped download record. File contents are never read by this API. Path is present only for a completed download whose GUID-named file is safely inside the configured download directory.

type Hint

type Hint struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	X     int    `json:"x"`
	Y     int    `json:"y"`
	CX    int    `json:"cx"`
	CY    int    `json:"cy"`
	Kind  string `json:"kind"`
}

Hint is one clickable/focusable target. CX/CY are viewport CSS pixels.

type IdentityOptions added in v0.2.0

type IdentityOptions struct {
	Stealth   bool
	UserAgent string
}

IdentityOptions controls the per-target browser identity override. Stealth is deliberately narrow: it removes Chromium's simple headless user-agent marker while retaining the browser's real version and platform. kitty-browse enables it by default because sites routinely block the headless token outright; it is still not a promise to bypass bot detection, challenges, or other site security controls.

type InterventionInfo added in v0.2.12

type InterventionInfo struct {
	Reason     string
	RetryAfter time.Time
}

type LaunchOptions added in v0.2.0

type LaunchOptions struct {
	ExecutablePath string
	ProfileDir     string
	DownloadDir    string
	// ProxyServer is an explicit Chromium proxy. Ambient HTTP_PROXY variables
	// are deliberately not read; callers must opt in with a reviewed value.
	ProxyServer string
	UserAgent   string
	Private     bool
	Stealth     bool
	// BrowserOutput receives Chromium's diagnostic output only when explicitly
	// provided. Private mode ignores it, just like kitty-browse's debug log.
	BrowserOutput  io.Writer
	RequireSandbox bool
}

LaunchOptions controls the Chromium process created from the returned allocator context. Stealth is on by default in kitty-browse, so the process UA is the browser's real one with only the headless token removed. An empty UserAgent lets that normalization happen; a non-empty one takes precedence.

type PopupWaitToken added in v0.2.0

type PopupWaitToken uint64

PopupWaitToken is a per-Session event sequence. Call BeginPopupWait before an operation which may open a window, then pass the result as sinceToken to WaitForPopup to exclude popups which predate that operation.

type ProfileInfo added in v0.2.0

type ProfileInfo struct {
	Dir         string
	DownloadDir string
	Private     bool
	StatePath   string
}

ProfileInfo describes the kitty-browse-owned data associated with a browser context. Private contexts do not have persistent profile or state paths.

func NewBrowserContext added in v0.2.0

func NewBrowserContext(parent context.Context, opts LaunchOptions) (context.Context, context.CancelFunc, ProfileInfo, error)

NewBrowserContext creates a chromedp exec-allocator context. Persistent contexts use a kitty-browse profile protected by a non-blocking process lock; private contexts leave user-data-dir unset so chromedp creates and removes a temporary directory when Chromium actually starts.

type ScrollFunc added in v0.2.0

type ScrollFunc func(ctx context.Context, x, y, deltaY float64) error

ScrollFunc sends one accumulated wheel movement. Implementations must honor ctx cancellation; at most one call is made at a time.

type ScrollStats added in v0.2.0

type ScrollStats struct {
	Inputs        uint64
	CDPCalls      uint64
	Merged        uint64
	DroppedInputs uint64
	DroppedDeltaY float64
	PendingDeltaY float64
	InFlight      bool
	Stopped       bool
}

ScrollStats is a race-safe snapshot of a Scroller.

type Scroller added in v0.2.0

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

Scroller coalesces high-frequency wheel input into one serial dispatch per display frame. It owns exactly one worker goroutine, irrespective of the number of calls to Push.

func NewScroller added in v0.2.0

func NewScroller(parent context.Context, dispatch ScrollFunc) *Scroller

NewScroller starts a frame-paced scroll dispatcher. A nil dispatch is permitted (and treated as a no-op), which is useful while a target changes.

func (*Scroller) Busy added in v0.2.0

func (s *Scroller) Busy() bool

Busy reports pending or in-flight work, and remains true briefly after the latest input. The grace period lets a UI avoid competing screenshot/title requests while a touchpad gesture is still arriving.

func (*Scroller) Err added in v0.2.0

func (s *Scroller) Err() error

Err returns the first dispatch error, if any.

func (*Scroller) Push added in v0.2.0

func (s *Scroller) Push(x, y, deltaY float64)

Push records wheel input without waiting for the worker or CDP. Coordinates use latest-pointer semantics. Same-direction movement is accumulated in full. On a direction reversal, unsent movement in the old direction is discarded so stale momentum cannot run for seconds behind the user's hand.

func (*Scroller) Stats added in v0.2.0

func (s *Scroller) Stats() ScrollStats

Stats returns a consistent snapshot. PendingDeltaY is signed; positive is downward. Merged counts input events combined behind another input in a completed CDP call. Movement discarded by reversal or Stop is reported separately.

func (*Scroller) Stop added in v0.2.0

func (s *Scroller) Stop()

Stop cancels an in-flight dispatch and drops unsent movement. It is idempotent and does not wait for a misbehaving ScrollFunc to return.

type Session

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

Session is one headless Chromium tab.

func Open

func Open(parent context.Context, target string, timeout time.Duration) (*Session, error)

Open starts Chromium, navigates to target and waits for the document body. target accepts a bare host as https, as well as the exact URL about:blank.

func (*Session) Automate added in v0.2.0

func (s *Session) Automate(ctx context.Context, name string, params json.RawMessage) (json.RawMessage, error)

Automate executes one native CDP automation command. The browser lifetime always remains bound to s.ctx; ctx only shortens this operation.

func (*Session) Back

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

Back moves one entry back. It is a no-op at the start of history.

func (*Session) BeginPopupWait added in v0.2.0

func (s *Session) BeginPopupWait() PopupWaitToken

BeginPopupWait returns the current popup event sequence. It has no browser side effects and is safe to call immediately before the action that may open a popup.

func (*Session) BlurFocused added in v0.2.0

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

BlurFocused clears page focus so browser shortcuts take over again.

func (*Session) CanBack

func (s *Session) CanBack() bool

CanBack reports whether history has an earlier entry.

func (*Session) CanForward

func (s *Session) CanForward() bool

CanForward reports whether history has a later entry.

func (*Session) ClearHints

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

ClearHints removes the page overlay and the data attributes.

func (*Session) Click

func (s *Session) Click(x, y float64) error

Click sends a left click at viewport CSS coordinates: move, press, release. The move lets mouseover-bound menus and handlers activate before the press.

func (*Session) Close

func (s *Session) Close()

Close closes this tab. A root session closes Chromium gracefully so persistent cookies/storage can be flushed before the allocator releases the profile lock.

func (*Session) Context

func (s *Session) Context() context.Context

Context is the chromedp context to hand to termcast and future controls.

func (*Session) EditableFocus added in v0.2.0

func (s *Session) EditableFocus(ctx context.Context) (bool, error)

EditableFocus reports whether a page element that accepts text is focused. While it is true, printable keys must be typed into the page rather than interpreted as browser shortcuts.

func (*Session) Forward

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

Forward moves one entry forward. It is a no-op at the end of history.

func (*Session) HandleJavaScriptDialog added in v0.2.0

func (s *Session) HandleJavaScriptDialog(ctx context.Context, accept bool, promptText string) error

HandleJavaScriptDialog accepts or dismisses the currently open dialog. The prompt text is passed directly to CDP and is neither retained nor logged.

func (*Session) Hints

func (s *Session) Hints(ctx context.Context, max int) ([]Hint, error)

Hints collects visible clickable/focusable elements and injects a label overlay into the page. The overlay is part of the next rendered frame.

func (*Session) History

func (s *Session) History() ([]string, int)

History returns the owned history and the current index.

func (*Session) InsertText added in v0.2.0

func (s *Session) InsertText(value string) error

InsertText inserts text into the focused element as IME input would. The terminal delivers composed UTF-8 runes, so this is the only safe path for Chinese text: synthesizing one key event per character would require a keyboard layout that does not exist.

func (*Session) Inspect added in v0.2.0

func (s *Session) Inspect(ctx context.Context, name string, params json.RawMessage) (json.RawMessage, error)

Inspect performs a read or state action against this Session's target. The caller context can cancel an operation without becoming the target's owner.

func (*Session) Intervention added in v0.2.7

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

Intervention reports only explicit, visible verification/limit UI or a 429 on the current document. It never returns page text or treats an unrelated image/analytics 429, login form or an article mentioning CAPTCHAs as a block.

func (*Session) InterventionDetails added in v0.2.12

func (s *Session) InterventionDetails(ctx context.Context) (InterventionInfo, error)

func (*Session) JavaScriptDialogStatus added in v0.2.0

func (s *Session) JavaScriptDialogStatus() (DialogStatus, error)

JavaScriptDialogStatus reports the currently blocking dialog, if any.

func (*Session) KeyPress added in v0.2.0

func (s *Session) KeyPress(name string) error

KeyPress sends one editing key to the page's focused element.

func (*Session) LayoutWidth added in v0.2.0

func (s *Session) LayoutWidth(ctx context.Context) (int, error)

LayoutWidth reports the page's layout width in CSS pixels: the wider of the viewport and the document's scroll extent. Callers use it to give fixed-width desktop pages a viewport wide enough to show the whole layout instead of clipping it at the pane edge.

func (*Session) ListDownloads added in v0.2.0

func (s *Session) ListDownloads() ([]Download, error)

ListDownloads returns up to the latest 64 browser-scoped records without consuming them.

func (*Session) LoadError added in v0.2.1

func (s *Session) LoadError() error

LoadError is the navigation failure the session survived, or nil. The page on screen is Chromium's error page for that failure.

func (*Session) MouseCancel added in v0.2.19

func (s *Session) MouseCancel(x, y float64) error

MouseCancel ends a held press without synthesizing a click.

func (*Session) MouseDown added in v0.2.0

func (s *Session) MouseDown(x, y float64) error

MouseDown moves the pointer to x,y and presses the left button, starting a drag that MouseMove continues and MouseUp ends. Sliders and canvas widgets only respond to this press/move/release sequence; a plain click cannot move them.

func (*Session) MouseHover added in v0.2.9

func (s *Session) MouseHover(x, y float64) error

MouseHover moves the pointer without pressing a button.

func (*Session) MouseMove added in v0.2.0

func (s *Session) MouseMove(x, y float64) error

MouseMove drags the left button to x,y.

func (*Session) MouseUp added in v0.2.0

func (s *Session) MouseUp(x, y float64) error

MouseUp releases the left button at x,y.

func (*Session) Navigate

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

Navigate loads target and makes it the current history entry.

func (*Session) Reload

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

Reload reloads the current URL without adding a history entry.

func (*Session) Screenshot added in v0.2.0

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

Screenshot captures the current viewport, or the complete scrollable page.

The browser remains bound to the Session context. The supplied context is used only to cancel this operation; its values are deliberately not passed to chromedp. Every capture also has a ten-second upper bound.

func (*Session) Scroll

func (s *Session) Scroll(x, y, deltaY float64) error

Scroll sends a wheel event at viewport CSS coordinates. Positive deltaY scrolls down.

func (*Session) ScrollContext added in v0.2.0

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

ScrollContext sends one wheel event through this Session's persistent target while respecting ctx cancellation. Each CDP operation is capped at 400ms.

func (*Session) SetViewport

func (s *Session) SetViewport(width, height int) error

SetViewport matches the Chromium viewport to the page area's pixels, so terminal cells map to CSS pixels without a second scale factor.

func (*Session) StartObservation added in v0.2.0

func (s *Session) StartObservation() error

StartObservation enables native CDP collection for this tab. It must be called after the target has been initialized and before its first load.

func (*Session) StopObservation added in v0.2.0

func (s *Session) StopObservation()

StopObservation stops retaining events and immediately releases all observations. The chromedp listener itself is tied to the Session context.

func (*Session) Sync added in v0.2.0

func (s *Session) Sync(ctx context.Context) (title string, err error)

Sync refreshes the session URL and history from Chromium and returns the current history entry's title. It uses the session's lifetime context while respecting ctx cancellation, and is bounded to one second for UI polling.

func (*Session) TargetID added in v0.2.0

func (s *Session) TargetID() string

TargetID is the tab's opaque stable CDP id. No remote debugging listener is required: automation uses the existing private Chromium pipe connection.

func (*Session) Text

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

Text returns the rendered page's innerText. It is the readable fallback when a page is unreadable as pixels or the user needs selectable text.

func (*Session) Title

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

Title returns document.title.

func (*Session) URL

func (s *Session) URL() string

URL is the normalized URL the session opened.

func (*Session) WaitDownload added in v0.2.0

func (s *Session) WaitDownload(ctx context.Context, guid string) (Download, error)

WaitDownload waits for a GUID, or for the newest unconsumed download begun in the preceding five seconds. Download observations are browser-scoped: a wait issued through any tab may match a download initiated by any tab.

func (*Session) WaitForPopup added in v0.2.0

func (s *Session) WaitForPopup(ctx context.Context, params json.RawMessage) (json.RawMessage, error)

WaitForPopup waits for one unconsumed page opened by this Session. With no sinceToken it considers only popups from the preceding five seconds, allowing the common click-then-wait flow without accidentally returning old windows. A matching popup is consumed exactly once. This method never attaches to, activates, or otherwise manages the popup target.

func (*Session) WaitFunction added in v0.2.0

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

WaitFunction repeatedly evaluates an expression and waits for a truthy result. Promise results are awaited by CDP before truthiness is tested.

func (*Session) WaitLoadState added in v0.2.0

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

WaitLoadState waits for the current top document to reach a native document ready state. networkidle is intentionally not supported.

func (*Session) WaitURL added in v0.2.0

func (s *Session) WaitURL(ctx context.Context, pattern string, exact bool) (string, error)

WaitURL waits for the top-frame URL. A non-exact pattern containing '*' or '?' is a whole-URL glob (wildcards include '/'); other patterns are substrings.

type Tabs added in v0.2.0

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

Tabs owns a set of user-visible tabs in one persistent Chromium browser. A private about:blank anchor keeps the browser alive independently of every user tab.

func OpenScopedTabs added in v0.2.11

func OpenScopedTabs(parent context.Context, target string, timeout time.Duration) (*Tabs, error)

OpenScopedTabs creates an independent tab collection within an already running Chromium. Reconciliation adopts only popups of its own pages; other collections' pages and browser-lifetime anchors remain invisible.

func OpenTabs added in v0.2.0

func OpenTabs(parent context.Context, target string, timeout time.Duration) (*Tabs, error)

OpenTabs starts one shared Chromium browser and opens the initial user tab.

func OpenTabsWithReady added in v0.2.3

func OpenTabsWithReady(parent context.Context, target string, timeout time.Duration, ready func()) (*Tabs, error)

OpenTabsWithReady marks the CDP startup boundary after the about:blank anchor is connected, BEFORE navigating to any user page.

func (*Tabs) Active added in v0.2.0

func (t *Tabs) Active() *Session

Active returns the selected user tab, or nil after Close.

func (*Tabs) Close added in v0.2.0

func (t *Tabs) Close()

Close closes all user tabs and then the private browser anchor.

func (*Tabs) CloseTab added in v0.2.0

func (t *Tabs) CloseTab(index int) error

CloseTab closes one user tab. The final user tab cannot be closed.

func (*Tabs) Index added in v0.2.0

func (t *Tabs) Index() int

Index returns the selected user-tab index, or -1 after Close.

func (*Tabs) New added in v0.2.0

func (t *Tabs) New(ctx context.Context, target string, timeout time.Duration) error

New creates, loads, and selects a user tab without replacing the browser.

func (*Tabs) Reconcile added in v0.2.0

func (t *Tabs) Reconcile(ctx context.Context) (bool, error)

Reconcile synchronizes user-visible tabs with Chromium's current page targets. It attaches window.open/automation-created pages without navigating them, removes targets closed by another CDP client, and never exposes the private browser-lifetime anchor. It returns whether the tab collection or selection changed.

Reconcile is intended to run on the UI goroutine. It still takes the Tabs write lock so concurrent control-server screenshots cannot race an attach, removal, or active-tab change. Only popups opened by a known page are selected; restored or browser-internal pages cannot steal the active tab.

func (*Tabs) Screenshot added in v0.2.0

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

Screenshot safely captures the selected tab. Holding the read lock for the entire capture prevents Select, CloseTab, and Close from changing or closing the target midway through a control-server request.

func (*Tabs) Select added in v0.2.0

func (t *Tabs) Select(index int) error

Select activates an existing tab without navigating or reloading it.

func (*Tabs) Sessions added in v0.2.0

func (t *Tabs) Sessions() []*Session

Sessions returns a copy of the user-tab slice. The anchor is never exposed.

Jump to

Keyboard shortcuts

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