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 ¶
- Variables
- func DefaultProfileDir() (string, error)
- func HintLabels(n int) []string
- func Normalize(raw string) (string, error)
- func PruneStalePrivateProfiles(now time.Time)
- type AutomationError
- type DialogStatus
- type Download
- type Hint
- type IdentityOptions
- type InterventionInfo
- type LaunchOptions
- type PopupWaitToken
- type ProfileInfo
- type ScrollFunc
- type ScrollStats
- type Scroller
- type Session
- func (s *Session) Automate(ctx context.Context, name string, params json.RawMessage) (json.RawMessage, error)
- func (s *Session) Back(ctx context.Context, timeout time.Duration) error
- func (s *Session) BeginPopupWait() PopupWaitToken
- func (s *Session) BlurFocused(ctx context.Context) error
- func (s *Session) CanBack() bool
- func (s *Session) CanForward() bool
- func (s *Session) ClearHints(ctx context.Context) error
- func (s *Session) Click(x, y float64) error
- func (s *Session) Close()
- func (s *Session) Context() context.Context
- func (s *Session) EditableFocus(ctx context.Context) (bool, error)
- func (s *Session) Forward(ctx context.Context, timeout time.Duration) error
- func (s *Session) HandleJavaScriptDialog(ctx context.Context, accept bool, promptText string) error
- func (s *Session) Hints(ctx context.Context, max int) ([]Hint, error)
- func (s *Session) History() ([]string, int)
- func (s *Session) InsertText(value string) error
- func (s *Session) Inspect(ctx context.Context, name string, params json.RawMessage) (json.RawMessage, error)
- func (s *Session) Intervention(ctx context.Context) (string, error)
- func (s *Session) InterventionDetails(ctx context.Context) (InterventionInfo, error)
- func (s *Session) JavaScriptDialogStatus() (DialogStatus, error)
- func (s *Session) KeyPress(name string) error
- func (s *Session) LayoutWidth(ctx context.Context) (int, error)
- func (s *Session) ListDownloads() ([]Download, error)
- func (s *Session) LoadError() error
- func (s *Session) MouseCancel(x, y float64) error
- func (s *Session) MouseDown(x, y float64) error
- func (s *Session) MouseHover(x, y float64) error
- func (s *Session) MouseMove(x, y float64) error
- func (s *Session) MouseUp(x, y float64) error
- func (s *Session) Navigate(ctx context.Context, target string, timeout time.Duration) error
- func (s *Session) Reload(ctx context.Context, timeout time.Duration) error
- func (s *Session) Screenshot(ctx context.Context, fullPage bool) ([]byte, error)
- func (s *Session) Scroll(x, y, deltaY float64) error
- func (s *Session) ScrollContext(ctx context.Context, x, y, deltaY float64) error
- func (s *Session) SetViewport(width, height int) error
- func (s *Session) StartObservation() error
- func (s *Session) StopObservation()
- func (s *Session) Sync(ctx context.Context) (title string, err error)
- func (s *Session) TargetID() string
- func (s *Session) Text(ctx context.Context) (string, error)
- func (s *Session) Title(ctx context.Context) (string, error)
- func (s *Session) URL() string
- func (s *Session) WaitDownload(ctx context.Context, guid string) (Download, error)
- func (s *Session) WaitForPopup(ctx context.Context, params json.RawMessage) (json.RawMessage, error)
- func (s *Session) WaitFunction(ctx context.Context, script string) error
- func (s *Session) WaitLoadState(ctx context.Context, state string) error
- func (s *Session) WaitURL(ctx context.Context, pattern string, exact bool) (string, error)
- type Tabs
- func OpenScopedTabs(parent context.Context, target string, timeout time.Duration) (*Tabs, error)
- func OpenTabs(parent context.Context, target string, timeout time.Duration) (*Tabs, error)
- func OpenTabsWithReady(parent context.Context, target string, timeout time.Duration, ready func()) (*Tabs, error)
- func (t *Tabs) Active() *Session
- func (t *Tabs) Close()
- func (t *Tabs) CloseTab(index int) error
- func (t *Tabs) Index() int
- func (t *Tabs) New(ctx context.Context, target string, timeout time.Duration) error
- func (t *Tabs) Reconcile(ctx context.Context) (bool, error)
- func (t *Tabs) Screenshot(ctx context.Context, fullPage bool) ([]byte, error)
- func (t *Tabs) Select(index int) error
- func (t *Tabs) Sessions() []*Session
Constants ¶
This section is empty.
Variables ¶
var ErrLastTab = errors.New("cannot close the final tab")
ErrLastTab is returned when closing a tab would leave no user-visible tab.
var ErrNoHistory = errors.New("no history entry")
ErrNoHistory means Back/Forward had nowhere to go.
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
DefaultProfileDir returns kitty-browse's default, independent Chromium profile. It never points at or copies a user's regular Chrome profile.
func HintLabels ¶
HintLabels returns at most n labels: first the home-row keys, then pairs.
func Normalize ¶
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
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
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 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
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
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
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) Push ¶ added in v0.2.0
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.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is one headless Chromium tab.
func Open ¶
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) 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
BlurFocused clears page focus so browser shortcuts take over again.
func (*Session) CanForward ¶
CanForward reports whether history has a later entry.
func (*Session) ClearHints ¶
ClearHints removes the page overlay and the data attributes.
func (*Session) Click ¶
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) EditableFocus ¶ added in v0.2.0
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) HandleJavaScriptDialog ¶ added in v0.2.0
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 ¶
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) InsertText ¶ added in v0.2.0
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
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
KeyPress sends one editing key to the page's focused element.
func (*Session) LayoutWidth ¶ added in v0.2.0
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
ListDownloads returns up to the latest 64 browser-scoped records without consuming them.
func (*Session) LoadError ¶ added in v0.2.1
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
MouseCancel ends a held press without synthesizing a click.
func (*Session) MouseDown ¶ added in v0.2.0
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
MouseHover moves the pointer without pressing a button.
func (*Session) Screenshot ¶ added in v0.2.0
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 ¶
Scroll sends a wheel event at viewport CSS coordinates. Positive deltaY scrolls down.
func (*Session) ScrollContext ¶ added in v0.2.0
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 ¶
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
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
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
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 ¶
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) WaitDownload ¶ added in v0.2.0
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
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
WaitLoadState waits for the current top document to reach a native document ready state. networkidle is intentionally not supported.
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
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
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) 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
CloseTab closes one user tab. The final user tab cannot be closed.
func (*Tabs) New ¶ added in v0.2.0
New creates, loads, and selects a user tab without replacing the browser.
func (*Tabs) Reconcile ¶ added in v0.2.0
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
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.