browser

package
v1.0.41 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 27 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 provides browser automation via Chrome DevTools Protocol.

Index

Constants

View Source
const (
	DetachedReadyTimeout  = 15 * time.Second
	DetachedReadyInterval = 300 * time.Millisecond
	OwnedReadyTimeout     = 30 * time.Second
	OwnedReadyInterval    = 100 * time.Millisecond
)

Readiness timeouts for the two launch modes. A detached browser is the long-lived one Aviary's browser tools share, launched on demand inside a tool call; an owned browser is started cold for a run, often on a fresh or private profile, which takes several seconds on a slow machine.

Variables

View Source
var ErrProfileLocked = errors.New("browser profile is in use by another aviary instance")

ErrProfileLocked reports a profile another running Aviary instance already has a browser on.

Functions

func CloseOverDevTools added in v0.7.0

func CloseOverDevTools(ctx context.Context, wsURL string) error

CloseOverDevTools sends the browser its own clean-shutdown command. It writes the message to the browser's WebSocket by hand because a window with no pages left has nothing for chromedp to attach to, creating a tab to send it from would flash a new window, and chromedp's Browser refuses to send this command itself.

func DebugURL added in v0.7.0

func DebugURL(port int) string

DebugURL is the base URL of the DevTools endpoint on a given port.

func DefaultProfileDir added in v0.7.0

func DefaultProfileDir() string

DefaultProfileDir is the profile Aviary's browser uses when the browser settings name none: a browser directory alongside aviary.yaml.

func FilteredChromeDPErrorf added in v0.7.0

func FilteredChromeDPErrorf(format string, args ...any)

FilteredChromeDPErrorf is the chromedp error logger every Aviary browser context uses. chromedp reports events it cannot decode or has no case for, and browsers keep adding those: FedCM initiators, and DOM events such as `dom.topLayerElementsUpdated` that its node-tree bookkeeping does not model. They say nothing about Aviary's own work, so they are logged at debug level instead of being printed over a terminal a user is watching. Anything else chromedp reports is still surfaced.

func FindBinary added in v0.7.0

func FindBinary(override string) (string, error)

FindBinary returns the browser executable to launch. An override is resolved through PATH so a bare command name works as well as a full path, and a bad one is reported instead of being silently replaced by a discovered browser: a user who named a browser meant that browser.

func FreePort added in v0.7.0

func FreePort() (int, error)

FreePort reserves a port for a browser's DevTools endpoint by letting the OS assign one and closing the listener again. Several Aviary instances can run owned browsers at once, so a fixed port would have them collide on the endpoint and drive each other's browser.

func LaunchArgs added in v0.7.0

func LaunchArgs(userDataDir string, port int, headless bool) []string

LaunchArgs are the flags Aviary launches a browser with. The new headless mode is asked for by name because it is the one that behaves like a real browser; the first-run and default-browser prompts would otherwise block a fresh profile from ever reaching the DevTools endpoint. A headed launch drops the headless flags so a window actually appears, and keeps everything else so it lands on the same profile and DevTools endpoint.

func WaitForPageTarget added in v0.7.0

func WaitForPageTarget(ctx context.Context, baseURL string, timeout, interval time.Duration) (string, error)

WaitForPageTarget returns the id of a page the browser already has open, polling every interval until one appears or the timeout expires. A headed browser creates its first window alongside the DevTools endpoint, not before it, so a single read can miss it.

func WaitForReady added in v0.7.0

func WaitForReady(ctx context.Context, baseURL string, timeout, interval time.Duration) (string, error)

WaitForReady polls the DevTools endpoint every interval until the browser answers with the WebSocket to connect on, or the timeout expires. The endpoint refuses connections until the browser is genuinely ready, so polling it is the readiness check rather than a guess at a startup delay.

func WebSocketURL added in v0.7.0

func WebSocketURL(ctx context.Context, baseURL string) (string, error)

WebSocketURL asks the DevTools endpoint for the browser-level WebSocket URL.

Types

type ChromeTab

type ChromeTab struct {
	ID    string `json:"id"`
	Type  string `json:"type"`
	URL   string `json:"url"`
	Title string `json:"title"`
}

ChromeTab represents a single open tab from Chrome's /json/list endpoint.

func PageTargets added in v0.7.0

func PageTargets(ctx context.Context, baseURL string) ([]ChromeTab, error)

PageTargets asks the DevTools endpoint for its targets and returns the pages among them. Anything that is not a page -- the DevTools front-end itself, service workers, extension backgrounds -- is skipped: they are not tabs.

type Manager

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

Manager manages browser sessions via Chrome DevTools Protocol. Each operation connects to Chrome on demand — no persistent in-process session is held between calls, which allows CLI invocations to share a single Chrome process via tab IDs.

func NewManager

func NewManager(binary string, cdpPort int, profileDir string, headless bool, reuseTabs ...bool) *Manager

NewManager creates a browser Manager. binary is the path to the Chromium/Chrome executable (empty = auto-detect). cdpPort is the remote debugging port (0 = default 9222). profileDir is the Chrome profile-directory name (empty = "Default"). headless controls whether the browser window is shown (false = visible). reuseTabs controls whether Open reuses an existing tab when the URL matches exactly. When reuseTabs is omitted it defaults to true.

func (*Manager) Click

func (m *Manager) Click(ctx context.Context, tabID, selector string) error

Click clicks the element matching selector in the given tab.

func (*Manager) Close

func (m *Manager) Close()

Close is a no-op: Chrome and its tabs run independently of this Manager.

func (*Manager) CloseTab

func (m *Manager) CloseTab(tabID string) error

CloseTab closes the given tab via the CDP /json/close endpoint and removes its cached session.

func (*Manager) EvalJS

func (m *Manager) EvalJS(ctx context.Context, tabID, expr string) (string, error)

EvalJS evaluates JavaScript in the given tab and returns the result as a string.

func (*Manager) Fill

func (m *Manager) Fill(ctx context.Context, tabID, selector, text string) error

Fill sets the value of the element matching selector in the given tab.

func (*Manager) Navigate

func (m *Manager) Navigate(ctx context.Context, tabID, url string) error

Navigate navigates an existing tab to url, waiting for the page to load.

func (*Manager) Open

func (m *Manager) Open(ctx context.Context, url string) (string, error)

Open navigates to url in a new Chrome tab, launching Chrome if necessary. It returns the CDP target ID of the new tab, which callers must pass to subsequent operations (Click, Type, Screenshot, EvalJS) to target that tab. Chrome and the tab persist after this call returns.

func (*Manager) Resize

func (m *Manager) Resize(ctx context.Context, tabID string, width, height int) error

Resize resizes the browser window that contains the given tab, if supported by the browser's CDP implementation.

func (*Manager) Screenshot

func (m *Manager) Screenshot(ctx context.Context, tabID string) ([]byte, error)

Screenshot captures the current page in the given tab as PNG bytes.

func (*Manager) Tabs

func (m *Manager) Tabs() ([]ChromeTab, error)

Tabs returns all currently open page tabs in the browser. Returns an error if Chrome is not running.

func (*Manager) Type

func (m *Manager) Type(ctx context.Context, tabID, selector, text string) error

Type types text into the element matching selector in the given tab.

func (*Manager) WaitVisible

func (m *Manager) WaitVisible(ctx context.Context, tabID, selector string, timeout time.Duration) error

WaitVisible waits until the element matching selector is visible in the given tab.

type OwnedBrowser added in v0.7.0

type OwnedBrowser struct {
	Child *OwnedChild
	Port  int
	WSURL string
	// Profile is the profile the browser was launched for, so the saved
	// sign-in is kept in one place whichever directory the browser runs in.
	Profile string
	// DataDir is the --user-data-dir the browser actually runs in: Profile
	// itself when this instance holds it, or a private directory of its own
	// when another Aviary instance or Aviary's own browser already does.
	DataDir string
	// contains filtered or unexported fields
}

OwnedBrowser is a browser Aviary launched for itself, beside the detached one Manager shares: it answers on a random free port, runs as a supervised child that dies with its owner, and is shut down cleanly over DevTools.

func LaunchOwned added in v0.7.0

func LaunchOwned(ctx context.Context, options OwnedOptions) (*OwnedBrowser, error)

LaunchOwned starts an owned browser and waits for its DevTools endpoint to answer. ctx bounds the launch only: canceling it later does not kill the browser, because the owner closes it cleanly on its way out and a kill would skip the shutdown that writes the profile to disk.

func (*OwnedBrowser) BaseURL added in v0.7.0

func (b *OwnedBrowser) BaseURL() string

BaseURL is the browser's DevTools endpoint.

func (*OwnedBrowser) Release added in v0.7.0

func (b *OwnedBrowser) Release()

Release gives up the profile claim, or removes the private directory the browser ran in instead. It runs once the browser is stopped, because a running browser still holds the directory.

func (*OwnedBrowser) Stop added in v0.7.0

func (b *OwnedBrowser) Stop()

Stop shuts the browser down, cleanly when it will go, and then gives up whatever it was run in.

type OwnedChild added in v0.7.0

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

OwnedChild is a browser process Aviary started and is waiting on.

func StartOwned added in v0.7.0

func StartOwned(supervisor Supervisor, shutdown ShutdownPolicy, cmd *exec.Cmd) (*OwnedChild, error)

StartOwned starts cmd through supervisor and waits on it in the background, so a shutdown can wait for the exit with a deadline. A nil supervisor runs cmd as a plain child process.

func (*OwnedChild) Exited added in v0.7.0

func (c *OwnedChild) Exited() <-chan struct{}

Exited is closed once the process has exited.

func (*OwnedChild) Stop added in v0.7.0

func (c *OwnedChild) Stop(wsURL string)

Stop asks the browser to shut down over its DevTools WebSocket and waits for it to do so, because only a clean shutdown writes out the profile state it is still holding in memory. The process is killed only if it is still there when the wait runs out, or at once when there is no endpoint to ask because the browser never came up. A request that fails gets a shorter wait: the browser may already be on its way out, but nothing is coming to shut it down.

func (*OwnedChild) WaitErr added in v0.7.0

func (c *OwnedChild) WaitErr() error

WaitErr is how the process exited. It is valid once Exited is closed.

type OwnedOptions added in v0.7.0

type OwnedOptions struct {
	// Binary is an explicit browser executable; empty discovers one.
	Binary string
	// Profile is the profile directory the browser is launched for.
	Profile string
	// Headed launches a visible window instead of a headless browser.
	Headed bool
	// Supervisor ties the process to its owner; nil runs a plain child.
	Supervisor Supervisor
	// Shutdown is how the browser is stopped.
	Shutdown ShutdownPolicy
}

OwnedOptions configures an owned browser launch.

type ProfileLock added in v0.7.0

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

ProfileLock is a held claim on a browser profile.

func ClaimProfile added in v0.7.0

func ClaimProfile(profile string) (*ProfileLock, string, error)

ClaimProfile decides which user-data directory a launch runs the browser against. Chrome allows one process per --user-data-dir, and a second one launched on a directory already in use hands itself to the first and exits, so a second Aviary instance on the same profile never saw its own DevTools endpoint come up and failed with "context deadline exceeded" (issue #663). The first instance takes the profile itself; any other runs its browser in a private directory of its own, and still starts signed in because the saved sign-in is read from and written to the shared profile, not the directory the browser happens to run in.

The same applies when Aviary's own browser (the one its browser tools drive) is already running on the profile: Code Loop shares that profile by default, so it runs beside that browser in a private directory instead.

func LockProfile added in v0.7.0

func LockProfile(profile string) (*ProfileLock, error)

LockProfile claims a profile for this process's browser, failing with a *ProfileLockedError, which matches ErrProfileLocked, when this or another instance already holds it.

func (*ProfileLock) Release added in v0.7.0

func (l *ProfileLock) Release()

Release gives the profile up. Closing the file drops the lock with it.

func (*ProfileLock) SetDevTools added in v0.7.32

func (l *ProfileLock) SetDevTools(baseURL string)

SetDevTools records the DevTools endpoint of the browser running on the held profile, so another claim from this process can reuse that browser instead of failing, and one from another instance can name it.

type ProfileLockedError added in v0.7.32

type ProfileLockedError struct {
	// Owner is the holder, nil when it left no record.
	Owner *ProfileOwner
	// Self reports that this process holds the profile itself, for example
	// for a Code Loop or Projects sign-in browser.
	Self bool
}

ProfileLockedError is a claim refused because the profile is already held. It matches ErrProfileLocked.

func (*ProfileLockedError) Error added in v0.7.32

func (e *ProfileLockedError) Error() string

func (*ProfileLockedError) Is added in v0.7.32

func (e *ProfileLockedError) Is(target error) bool

Is makes the error match ErrProfileLocked.

type ProfileOwner added in v0.7.32

type ProfileOwner struct {
	PID       int       `json:"pid"`
	Hostname  string    `json:"hostname,omitempty"`
	Started   time.Time `json:"started"`
	ConfigDir string    `json:"config_dir,omitempty"`
	// DevTools is the DevTools endpoint of the browser the holder runs on the
	// profile, once it answers.
	DevTools string `json:"devtools,omitempty"`
}

ProfileOwner describes the process holding a profile lock.

func (ProfileOwner) String added in v0.7.32

func (o ProfileOwner) String() string

String names the owner for an error message or a status line.

type ProfileStatus added in v0.7.32

type ProfileStatus struct {
	// Held reports that a running Aviary instance holds the profile.
	Held bool
	// Owner is the holder when Held, or the exited run whose record was
	// cleared when Reclaimed.
	Owner *ProfileOwner
	// Reclaimed reports that a record left by an exited run was cleared.
	Reclaimed bool
	// ChromeRunning reports that a browser, such as Aviary's detached one,
	// runs on the profile without holding the lock.
	ChromeRunning bool
}

ProfileStatus is the state of a browser profile's lock, for diagnostics.

func InspectProfile added in v0.7.32

func InspectProfile(profile string) (ProfileStatus, error)

InspectProfile reports who holds profile. A record left by a run that has exited is cleared along the way, since the lock itself is already free.

type Session

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

Session wraps a chromedp browser context for a single automation session.

func (*Session) Click

func (s *Session) Click(selector string) error

Click clicks an element matching the CSS selector.

func (*Session) Close

func (s *Session) Close()

Close tears down the session context and allocator. Depending on how the session was created, this may close the tab.

func (*Session) Detach

func (s *Session) Detach()

Detach disconnects from the browser without explicitly canceling the task context. This is used for operations attached to an existing tab where we must avoid closing the target on cleanup.

func (*Session) EvalJS

func (s *Session) EvalJS(expr string) (string, error)

EvalJS evaluates JavaScript and returns a text representation of the result.

func (*Session) Fill

func (s *Session) Fill(selector, text string) error

Fill sets the value of the element matching selector.

func (*Session) Navigate

func (s *Session) Navigate(url string) error

Navigate goes to the given URL.

func (*Session) ResizeWindow

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

ResizeWindow resizes the browser window that contains the tab this session is attached to. Not all browsers or environments support setting window bounds via CDP; callers should handle errors accordingly.

func (*Session) Run

func (s *Session) Run(steps ...chromedp.Action[chromedp.Void]) error

Run executes chromedp actions that return no value within the session.

func (*Session) Screenshot

func (s *Session) Screenshot() ([]byte, error)

Screenshot captures the full page as PNG bytes.

func (*Session) TabID

func (s *Session) TabID() string

TabID returns the CDP target ID for the tab this session is attached to.

func (*Session) Type

func (s *Session) Type(selector, text string) error

Type clears the element matching selector and types text into it.

func (*Session) WaitVisible

func (s *Session) WaitVisible(selector string, timeout time.Duration) error

WaitVisible waits until an element matching the CSS selector is visible.

type ShutdownPolicy added in v0.7.0

type ShutdownPolicy struct {
	Timeout     time.Duration
	FailedGrace time.Duration
	Close       func(ctx context.Context, wsURL string) error
}

ShutdownPolicy is how an owned browser is stopped: asked over DevTools with Close, then killed if it has not exited within Timeout, or within the shorter FailedGrace when the request itself failed. Zero values use the defaults.

type Supervisor added in v0.7.0

type Supervisor interface {
	// Start starts cmd as an owned subprocess.
	Start(cmd *exec.Cmd) error
	// Wait waits for a started subprocess to exit and stops owning it.
	Wait(cmd *exec.Cmd) error
	// Kill ends a started subprocess and everything it spawned at once. It
	// only signals, so it is safe while another goroutine is in Wait.
	Kill(cmd *exec.Cmd) error
}

Supervisor starts, waits on, and kills an owned browser subprocess, so the caller decides how a browser is tied to its own lifetime. Chrome allows one process per --user-data-dir, and a browser left running holds the profile against the next launch.

Jump to

Keyboard shortcuts

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