engine

package
v0.1.0-alpha.6 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: Apache-2.0 Imports: 118 Imported by: 0

Documentation

Overview

Package engine is Sweef's browser core. It is intentionally *not* a fork of Blink/WebKit (which cost >100 MiB RSS before loading a page). Instead it is an agent-first micro-engine:

  • HTML5-compliant tokenizer/tree builder (golang.org/x/net/html)
  • CSS selector + cascade resolution for query/computed-style needs
  • A real JS runtime via embedded QuickJS (cgo, ~1.5 MiB heap idle)
  • Network stack with cookie jar, cache, HAR capture, request interception
  • Structured text renderer that fits 320x200 and up; optional PNG blit

Everything is exposed as small goroutine-per-tab state machines so a tab costs < 2 MiB instead of Chromium's ~60 MiB renderer process.

Index

Constants

View Source
const (
	PermCamera     = "camera"
	PermMicrophone = "microphone"
	PermDisplay    = "display-capture"
)

Permission names used by the broker and the Permissions API.

View Source
const (
	DefaultImageMaxBytes  = 200 << 10
	DefaultScriptMaxBytes = 300 << 10
	DefaultFontMaxBytes   = 300 << 10
	DefaultFontTotalBytes = 600 << 10
)

Default caps.

View Source
const (
	PermNotifications = "notifications"
	PermPush          = "push"
	PermPeriodicSync  = "periodic-background-sync"
)

Permission names the engine asks the embedder about.

View Source
const DefaultActivationWindow = 5 * time.Second

DefaultActivationWindow is how long a click or key press keeps allowing popups.

View Source
const (
	// DefaultMaxRSSMiB is the default soft budget: a daemon driving typical
	// pages one after another stays well under it (see README "Memory").
	DefaultMaxRSSMiB = 384
)
View Source
const PermClipboardRead = "clipboard-read"

PermClipboardRead is the permission name the engine asks the embedder about before a page may read the clipboard.

Variables

View Source
var (
	ErrNoTab    = errors.New("engine: no such tab")
	ErrClosed   = errors.New("engine: closed")
	ErrNotFound = errors.New("engine: node not found")
	ErrTimeout  = errors.New("engine: timeout waiting for condition")
)
View Source
var ErrNoFocus = errors.New("no element has keyboard focus: click or focus a field first, or pass a selector")

ErrNoFocus is returned when keys are typed into a script-less page where no element has focus.

View Source
var ErrNotSkipped = errors.New("engine: node is not a Data Saver placeholder")

ErrNotSkipped is returned by LoadSkipped for a node that is not a placeholder.

Functions

func CleanTabTitle

func CleanTabTitle(s string) string

CleanTabTitle is document.title made safe for tab-state output: the characters badTabRune rejects become spaces, then whitespace is stripped and collapsed as document.title does.

func CleanTabURL

func CleanTabURL(s string) string

CleanTabURL percent-encodes the characters badTabRune rejects (a URL String() already escapes them; this guards the other ways a URL reaches tab state).

func GeneratePreludeBytecode

func GeneratePreludeBytecode() (bc []byte, key string, err error)

GeneratePreludeBytecode compiles the prelude the way compiledPrelude does and returns the bytecode and the key to embed with it (tools/genprelude).

func ProcessRSS

func ProcessRSS() (uint64, bool)

ProcessRSS is the resident set size of this process in bytes (VmRSS); ok is false when the OS does not say. It counts what the Go runtime does not see: the QuickJS heaps live in libc-allocated memory outside the Go heap.

func RegisterRTCTrackSource

func RegisterRTCTrackSource(trackID string, s RTCTrackSource)

RegisterRTCTrackSource says what feeds the track with this id (getUserMedia calls it for the tracks it creates). A sender created for the track opens its own source through it.

func SetHostMap

func SetHostMap(m map[string]string)

SetHostMap replaces the override table (host name -> IP address or host). Pass nil to clear it.

func SetLayoutCheck

func SetLayoutCheck(on bool)

SetLayoutCheck switches the SWEEF_LAYOUT_CHECK comparison on or off (tests).

func SetProcessMemoryBudget

func SetProcessMemoryBudget(mib int)

SetProcessMemoryBudget applies the budget to the Go runtime as a soft memory limit (once per process; the long-lived commands call it).

func SetRTCAudioProcessorFactory

func SetRTCAudioProcessorFactory(f func() rtcmedia.AudioProcessor)

SetRTCAudioProcessorFactory installs echo cancellation / noise suppression for calls: f is called once per peer connection, and the processor it returns hears what is played (far end) and cleans what is captured (near end). Sweef ships none; calls need headphones until one is provided.

func SetRTCAudioSinkFactory

func SetRTCAudioSinkFactory(f func() rtcmedia.AudioSink)

SetRTCAudioSinkFactory sets where received WebRTC audio goes: f is called for each remote audio track that is attached to a media element and returns the sink that plays it. The default discards audio; the audio output package supplies the real one.

func SetRTCTrackResolver

func SetRTCTrackResolver(f func(t *Tab, d RTCTrackDesc) (RTCTrackSource, bool))

SetRTCTrackResolver installs a function consulted for tracks that were not registered by id. The default handles canvas.captureStream() tracks, the fake devices (SWEEF_FAKE_MEDIA) and device ids known to internal/capture.

func SetWebRTCAllowWithProxy

func SetWebRTCAllowWithProxy(on bool)

SetWebRTCAllowWithProxy lets peer connections be created while an HTTP or SOCKS proxy is configured. WebRTC is UDP and cannot use the proxy, so by default the constructor throws NotSupportedError instead of silently bypassing it.

func SetWebRTCEnabled

func SetWebRTCEnabled(on bool)

SetWebRTCEnabled turns the RTCPeerConnection API on or off for pages loaded from now on (SWEEF_WEBRTC=off at start-up). Off removes the constructors, as in browsers that ship without WebRTC.

func SetWebRTCHostCandidates

func SetWebRTCHostCandidates(m WebRTCHostCandidates)

SetWebRTCHostCandidates sets the host candidate policy for peer connections created from now on. Also settable with SWEEF_WEBRTC_HOST_CANDIDATES=mdns|none|raw.

func UnregisterRTCTrackSource

func UnregisterRTCTrackSource(trackID string)

UnregisterRTCTrackSource forgets a track (call when the track is stopped or garbage).

Types

type AudioState

type AudioState struct {
	Audible bool `json:"audible"` // the tab played non-silent audio in the last 1.5 s (true while muted too, like a browser tab)
	Muted   bool `json:"muted"`   // the tab is muted by the browser (not by the page)
}

AudioState is the payload of EvAudio and the result of Tab.AudioState.

type Badge

type Badge struct {
	Set   bool  // a badge is shown
	Count int64 // 0 with Set true is the plain "flag" badge
}

Badge is the state of an origin's app badge.

type BindingCall

type BindingCall struct {
	SID  int64           `json:"sid"`
	Name string          `json:"name"`
	Args json.RawMessage `json:"args"`
	URL  string          `json:"url"`
	At   time.Time       `json:"at"`
}

BindingCall is one invocation of an exposed binding by page code.

type BitmapSource

type BitmapSource interface {
	// Bitmap returns the current contents (a snapshot is fine; callers must
	// not mutate it). Nil means "nothing drawn yet".
	Bitmap() image.Image
	// Size is the intrinsic size in pixels (canvas width/height attributes,
	// video videoWidth/videoHeight); 0,0 when unknown.
	Size() (w, h int)
}

BitmapSource is anything that can report its current pixels.

type BrowserContext

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

BrowserContext is the Playwright unit of isolation: its own cookie jar, storage state, UA/viewport/geolocation overrides and tab set. One Engine can host many contexts — agents spin up throw-away profiles per task for free.

func (*BrowserContext) AcceptLanguage

func (c *BrowserContext) AcceptLanguage() string

AcceptLanguage is the value in force for the context.

func (*BrowserContext) AddCookies

func (c *BrowserContext) AddCookies(items []map[string]any) error

AddCookies injects cookies (Playwright context.addCookies).

func (*BrowserContext) ClearCookies

func (c *BrowserContext) ClearCookies(name string)

ClearCookies drops the cookies called name, or every cookie (partitions included) when name is empty.

func (*BrowserContext) ClearSiteData

func (c *BrowserContext) ClearSiteData(origin string)

ClearSiteData deletes the IndexedDB databases, Cache Storage and service worker registrations of one origin ("" = every origin of the context). Open connections are closed by force.

An origin also clears the state kept for it inside other sites' partitions, and the state of the partitions whose top-level site it is: clearing a site's data clears everything keyed with it. localStorage, the Origin Private File System and partitioned cookies go with it.

func (*BrowserContext) ClearStorage

func (c *BrowserContext) ClearStorage(origin string)

func (*BrowserContext) Clipboard

func (c *BrowserContext) Clipboard() Clipboard

Clipboard returns the clipboard of the context.

func (*BrowserContext) Close

func (c *BrowserContext) Close() error

func (*BrowserContext) CountedTransport

func (c *BrowserContext) CountedTransport() http.RoundTripper

CountedTransport returns the RoundTripper the engine uses for the context (own cookie-free connection pool, socket counters, Content-Encoding decoding). Code outside the engine that makes requests for the person (favicons, downloads, update checks) can use it so that its traffic is part of WireIn/WireOut; requests made through any other client are not counted.

func (*BrowserContext) DataPolicy

func (c *BrowserContext) DataPolicy() DataPolicy

DataPolicy returns the context's policy.

func (*BrowserContext) DataStats

func (c *BrowserContext) DataStats() DataStats

DataStats returns what the context has used since it was created. WireIn and WireOut are exact socket totals; the rest is attribution (see DataStats).

func (*BrowserContext) DeleteCache

func (c *BrowserContext) DeleteCache()

DeleteCache forgets the HTTP cache entries of this context. For the default context that includes the on-disk cache, which is shared by the whole profile.

func (*BrowserContext) Fetch

func (c *BrowserContext) Fetch(method, urlStr string, headers map[string]string, body string) (int, map[string]string, string, error)

Fetch performs a context-scoped request (cookies + credentials apply) that does NOT change any tab's DOM — Playwright's APIRequestContext.

func (*BrowserContext) GetStorageValue

func (c *BrowserContext) GetStorageValue(origin, key string) (string, bool)

func (*BrowserContext) GrantThirdPartyCookies

func (c *BrowserContext) GrantThirdPartyCookies(topSite, embeddedSite string)

GrantThirdPartyCookies lets embeddedSite use unpartitioned cookies while embedded under topSite (what a granted document.requestStorageAccess() records; also the hook for a per-site exception list in the UI). Sites are schemeful ("https://example.com").

func (*BrowserContext) JarRef

func (c *BrowserContext) JarRef() *Jar

func (*BrowserContext) LoadState

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

LoadState restores cookies + storage from a storage-state JSON file.

func (*BrowserContext) Name

func (c *BrowserContext) Name() string

func (*BrowserContext) NewTab

func (c *BrowserContext) NewTab(urlStr string) (*Tab, error)

func (*BrowserContext) Options

func (c *BrowserContext) Options() ContextOptions

func (*BrowserContext) PWA

func (c *BrowserContext) PWA() *PWA

PWA returns the control handle of the context.

func (*BrowserContext) PartitionPolicy

func (c *BrowserContext) PartitionPolicy() PartitionPolicy

PartitionPolicy returns the context's cookie policy.

func (*BrowserContext) RemoveStorageValue

func (c *BrowserContext) RemoveStorageValue(origin, key string)

RemoveStorageValue deletes one key from an origin bucket.

func (*BrowserContext) ResetDataStats

func (c *BrowserContext) ResetDataStats()

ResetDataStats zeroes the context's attribution and cache/skip counters (the socket totals keep counting: they are the exact record).

func (*BrowserContext) RevokeThirdPartyCookies

func (c *BrowserContext) RevokeThirdPartyCookies(topSite, embeddedSite string)

RevokeThirdPartyCookies undoes GrantThirdPartyCookies.

func (*BrowserContext) SaveState

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

SaveState writes a Playwright-compatible storage_state JSON: cookies with proper domain/path/expiry/httpOnly/secure fields plus localStorage dumps.

func (*BrowserContext) ServiceWorkerConsole

func (c *BrowserContext) ServiceWorkerConsole(scope string) []Event

ServiceWorkerConsole returns the console log of a registration's active worker (nil when it has no running VM).

func (*BrowserContext) ServiceWorkers

func (c *BrowserContext) ServiceWorkers() []ServiceWorkerInfo

ServiceWorkers lists the context's registrations.

func (*BrowserContext) SetAgentLoading

func (c *BrowserContext) SetAgentLoading(on bool)

SetAgentLoading puts every tab of the context in agent loading mode (AgentPolicy) until turned off. A tab's own override still wins.

func (*BrowserContext) SetClipboard

func (c *BrowserContext) SetClipboard(cb Clipboard)

SetClipboard installs the clipboard the pages of this context use (nil: a memory clipboard of its own).

func (*BrowserContext) SetDataPolicy

func (c *BrowserContext) SetDataPolicy(p DataPolicy)

SetDataPolicy sets the context's Data Saver policy (all tabs inherit it unless they have their own override). The zero policy / SaverOff blocks nothing.

func (*BrowserContext) SetPWA

func (c *BrowserContext) SetPWA(o PWAOptions)

SetPWA connects the context to the application. It may be called once, before pages that use these APIs load.

func (*BrowserContext) SetPartitionPolicy

func (c *BrowserContext) SetPartitionPolicy(p PartitionPolicy)

SetPartitionPolicy replaces the context's cookie policy.

func (*BrowserContext) SetStorageValue

func (c *BrowserContext) SetStorageValue(origin, key, val string)

SetStorageValue records a key under an origin bucket (used by Storage API).

func (*BrowserContext) SiteStorage

func (c *BrowserContext) SiteStorage() *sitestore.Manager

SiteStorage is the context's origin-scoped storage (IndexedDB, Cache Storage, service worker data).

func (*BrowserContext) StorageKeys

func (c *BrowserContext) StorageKeys(origin string) []string

StorageKeys lists the keys stored for an origin, in insertion-independent order.

func (*BrowserContext) StorageStateDoc

func (c *BrowserContext) StorageStateDoc() map[string]any

StorageStateDoc returns the Playwright storage-state JSON document (cookies + origins) for this context, suitable for `state.save()`.

func (*BrowserContext) Tabs

func (c *BrowserContext) Tabs() []*Tab

type Bus

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

Bus fans out events to subscribers (MCP bridge, CDP shim, SDK sockets).

func NewBus

func NewBus() *Bus

func (*Bus) Publish

func (b *Bus) Publish(e Event)

func (*Bus) Subscribe

func (b *Bus) Subscribe(depth int) (uint64, <-chan Event)

func (*Bus) Unsubscribe

func (b *Bus) Unsubscribe(id uint64)

type Clipboard

type Clipboard interface {
	// Read returns every flavour currently on the clipboard (nil when it is empty).
	Read() ([]ClipboardEntry, error)
	// Write replaces the clipboard contents.
	Write([]ClipboardEntry) error
}

Clipboard is the system clipboard as the engine sees it. Implementations must be safe for concurrent use.

type ClipboardEntry

type ClipboardEntry struct {
	Type string
	Data []byte
}

ClipboardEntry is one flavour of the clipboard contents: a MIME type ("text/plain", "text/html", "image/png", "web text/custom") and its bytes.

type ClipboardWrite

type ClipboardWrite struct{ Origin string }

ClipboardWrite is the payload of EvClipboard.

type CompiledScript

type CompiledScript struct {
	Source string
	Name   string
}

CompiledScript is a script ready for the JS runtime.

type ContextOptions

type ContextOptions struct {
	UserAgent         string            `json:"userAgent,omitempty"`
	ViewportWidth     int               `json:"viewportWidth,omitempty"`
	ViewportHeight    int               `json:"viewportHeight,omitempty"`
	DeviceScaleFactor float64           `json:"deviceScaleFactor,omitempty"`
	Mobile            bool              `json:"mobile,omitempty"`
	Landscape         bool              `json:"landscape,omitempty"`
	Geolocation       *[2]float64       `json:"geolocation,omitempty"`
	Permissions       []string          `json:"permissions,omitempty"`
	Offline           bool              `json:"offline,omitempty"`
	ColorScheme       string            `json:"colorScheme,omitempty"`
	ExtraHeaders      map[string]string `json:"extraHTTPHeaders,omitempty"`
	HTTPCredentials   *[2]string        `json:"-"`
	ProxyURL          string            `json:"proxy,omitempty"` // overrides Options.ProxyURL and the environment for this context
	AcceptLanguage    string            `json:"acceptLanguage,omitempty"`
	StoragePath       string            `json:"storagePath,omitempty"` // load/save state JSON
	StorageDir        string            `json:"storageDir,omitempty"`  // persist IndexedDB, Cache Storage and service workers here ("" = memory only)
}
type Cookie struct {
	Name     string `json:"name"`
	Value    string `json:"value"`
	Domain   string `json:"domain"`
	Path     string `json:"path"`
	Expires  int64  `json:"expires"` // unix seconds; 0 = session cookie
	HttpOnly bool   `json:"httpOnly"`
	Secure   bool   `json:"secure"`
	SameSite int8   `json:"sameSite"` // 0 default,1 strict,2 lax,3 none
	Creation int64  `json:"creation"`
	// Partitioned is the Partitioned attribute (CHIPS): the cookie is keyed by the top-level site it was set under.
	Partitioned bool `json:"partitioned,omitempty"`
	// Partition is the top-level site ("https://example.com") the cookie is double-keyed with; "" = the unpartitioned
	// jar. Third-party contexts keep their cookies here (partition.go).
	Partition string `json:"partitionKey,omitempty"`
}

Cookie is our own cookie record so storage-state can round-trip the full attribute set (Chromium's http.Cookie loses SameSite=None + creation time).

func ParseSetCookie

func ParseSetCookie(h string, ctx *url.URL) *Cookie

ParseSetCookie converts a Set-Cookie header into our Cookie record.

type CookieMode

type CookieMode int

CookieMode is what a third-party context may do with cookies.

const (
	// CookiesPartitioned (the default): a third-party context sees and stores cookies in a jar of its own for the
	// top-level site. Nothing a third party set while embedded under site A is sent while it is embedded under B,
	// and the cookies it holds as a first party are never sent to it as an embed.
	CookiesPartitioned CookieMode = iota
	// CookiesBlocked: a third-party context sends and stores only cookies that carry the Partitioned attribute.
	CookiesBlocked
	// CookiesAllowed: no partitioning (third-party cookies behave as they did before this feature). Opt-out for
	// compatibility; every other rule of the policy table stays in force.
	CookiesAllowed
)

type DOMNode

type DOMNode struct {
	ID       int64       `json:"id"`
	Type     int         `json:"type"` // DOM nodeType: 1 element, 3 text, 8 comment, 9 document, 10 doctype
	Name     string      `json:"name"` // tag name (lower case) or #text, #comment, #document
	Attrs    [][2]string `json:"attrs,omitempty"`
	Value    string      `json:"value,omitempty"` // text, comment and doctype data (cut at 2000 bytes)
	Kids     int         `json:"kids"`            // children that appear in the tree (blank text nodes do not)
	Children []DOMNode   `json:"children,omitempty"`
	Frame    bool        `json:"frame,omitempty"` // an iframe: its document is separate and not shown
}

DOMNode is one node of the tree shown in the Elements panel.

type DataEvent

type DataEvent struct {
	Context string    // BrowserContext.ID
	Tab     DataStats // the tab's stats (zero value for context-level traffic)
	WireIn  int64     // exact socket totals of the context
	WireOut int64
}

DataEvent is the payload of EvData events.

type DataKind

type DataKind string

DataKind classifies a request for the stats.

const (
	KindDocument DataKind = "document"
	KindScript   DataKind = "script"
	KindStyle    DataKind = "style"
	KindImage    DataKind = "image"
	KindFont     DataKind = "font"
	KindMedia    DataKind = "media"
	KindXHR      DataKind = "xhr"
	KindFrame    DataKind = "frame"
	KindOther    DataKind = "other"
)

type DataPolicy

type DataPolicy struct {
	Level               SaverLevel
	ImageMaxBytes       int  // tap-to-load above this Content-Length (default 200<<10); 0 = no cap
	ScriptMaxBytes      int  // strict: total first-party script budget per page (default 300<<10); 0 = no budget
	LazyImages          bool // fetch only near the viewport
	BlockFonts          bool // strict: web fonts are not fetched, except icon fonts (webfonts.go)
	BlockMediaLoad      bool // no preload/autoplay; fetch on play only
	ClickToLoad3PFrames bool
	DropHints           bool // prefetch/preload/prerender/dns-prefetch
	SuspendBackground   bool // background tabs: no timers, no requests
	ExtendCache         bool
	SaveDataHeader      bool

	// Additive to the contract (strict mode needs them as separate switches so
	// that the agent preset can be "strict minus script limits").
	NoImages               bool // images only when tapped (placeholders keep their declared size)
	BlockThirdPartyScripts bool

	// Web font limits (webfonts.go). Zero means no limit / no restriction.
	FontMaxBytes   int  // one font file, transfer size (standard: 300 KB)
	FontTotalBytes int  // all fonts of a page, transfer size (standard: 600 KB); icon fonts are exempt
	FontWOFFOnly   bool // only WOFF2/WOFF sources are used (plain TrueType/OpenType files are skipped)
}

DataPolicy says what the engine may fetch and when. Level Off ignores every other field. PolicyFor gives the documented presets.

func AgentPolicy

func AgentPolicy() DataPolicy

AgentPolicy is the loading mode for agent-driven loads: strict (agents read the accessibility snapshot and never need images, fonts or media) minus the script limits (scripts often render the content an agent is after).

func PolicyFor

func PolicyFor(level SaverLevel) DataPolicy

PolicyFor returns the preset of a level (the table in docs/data-saver.md).

type DataStats

type DataStats struct {
	WireIn, WireOut int64
	ByKind          map[DataKind]int64
	ByOrigin        map[string]int64 // "scheme://host[:port]"
	CacheHitBytes   int64            // transfer bytes not downloaded because of a cache hit or a 304 (measured)
	AbortedBytes    int64            // bytes not read because Content-Length exceeded a cap (measured)
	Skipped         map[DataKind]int // requests skipped by policy
	SkippedEstimate int64            // ESTIMATED bytes avoided: always flag as an estimate

	// Additive to the contract.
	SkippedKnownBytes int64 // measured: size of blocked requests learned from the cache
	Requests          int64 // exchanges made (redirect hops and revalidations count)
}

DataStats is what a context or a tab has used and saved. Keys of ByKind and ByOrigin hold approximate transfer bytes (see wire.go); WireIn/WireOut of a BrowserContext are exact socket totals, those of a Tab are the sums of its attributed exchanges (approximate).

func (DataStats) MeasuredSaved

func (s DataStats) MeasuredSaved() int64

MeasuredSaved is everything that was actually measured as not downloaded.

func (DataStats) Used

func (s DataStats) Used() int64

Used is the exact socket total for a context (WireIn+WireOut).

type DevBox

type DevBox struct {
	Margin  [4]float64 `json:"margin"` // top right bottom left
	Border  [4]float64 `json:"border"`
	Padding [4]float64 `json:"padding"`
	W       float64    `json:"w"` // content box
	H       float64    `json:"h"`
	X       float64    `json:"x"` // border box position in the document
	Y       float64    `json:"y"`
	BW      float64    `json:"bw"` // border box size
	BH      float64    `json:"bh"`
}

DevBox is the box model of an element, in CSS px.

type DevCookie

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

DevCookie is a cookie the page's URL would send, for the Application panel.

type DevDecl

type DevDecl struct {
	Name       string `json:"name"`
	Value      string `json:"value"`
	Important  bool   `json:"important,omitempty"`
	Overridden bool   `json:"overridden,omitempty"` // a rule of higher priority sets the property too
}

DevDecl is one declaration of a rule.

type DevEvalResult

type DevEvalResult struct {
	OK   bool   `json:"ok"`
	Type string `json:"type,omitempty"` // typeof of the value, "null", "array", "node", ...
	Text string `json:"text"`
}

DevEvalResult is what the Console's prompt prints for an expression.

type DevRule

type DevRule struct {
	Selector string    `json:"selector"`
	Source   string    `json:"source"` // address or "<style> 2" or "element.style"
	Line     int       `json:"line,omitempty"`
	AtRules  []string  `json:"at,omitempty"` // @media / @supports conditions it sits in
	Inline   bool      `json:"inline,omitempty"`
	Decls    []DevDecl `json:"decls"`
	// contains filtered or unexported fields
}

DevRule is a rule that matches the selected element.

type DevSignals

type DevSignals struct {
	Console int64
	Net     int64
	Doc     uint64
	Nav     int64
}

DevSignals are cheap counters that change when Developer Tools has something new to fetch: console entries, network entries (added or completed), document mutations and navigations.

type DevStyle

type DevStyle struct {
	Rules    []DevRule   `json:"rules"`
	Computed [][2]string `json:"computed"`
	Box      *DevBox     `json:"box,omitempty"`
	Hidden   bool        `json:"hidden,omitempty"` // display:none: no box
}

DevStyle is everything the Styles / Computed panes show for one element.

type Dialog

type Dialog struct {
	Kind    string `json:"kind"` // alert | confirm | prompt | beforeunload
	Message string `json:"message"`
	URL     string `json:"url,omitempty"`
}

Dialog models a JS dialog (alert/confirm/prompt/beforeunload) the way Playwright surfaces page.on("dialog"). The engine records it in a ring and applies whatever response an agent armed beforehand.

func (Dialog) String

func (d Dialog) String() string

type DisplayInfo

type DisplayInfo struct {
	Label   string
	Surface string
	W, H    int // native size in pixels
}

DisplayInfo describes an opened display source.

type DisplaySource

type DisplaySource struct {
	ID      string
	Title   string
	URL     string
	Surface string // "browser" (a tab) or "window" (the whole browser window)
	Current bool   // the tab that is asking
	TabID   string
}

DisplaySource is one thing getDisplayMedia can share.

type Download

type Download struct {
	URL               string    `json:"url"`
	SuggestedFilename string    `json:"suggestedFilename"`
	Path              string    `json:"path"`
	Size              int64     `json:"size"`
	MimeType          string    `json:"mimeType,omitempty"`
	Error             string    `json:"error,omitempty"`
	At                time.Time `json:"at"`
}

Download describes one saved file.

type Engine

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

Engine owns tabs, the event bus, and global resources (cookie jar, cache).

func New

func New(opts Options) *Engine

func (*Engine) ActiveTab

func (e *Engine) ActiveTab() (*Tab, error)

ActiveTab returns the most recently created tab (single-window semantics).

func (*Engine) Bus

func (e *Engine) Bus() *Bus

func (*Engine) ClearHTTPCache

func (e *Engine) ClearHTTPCache()

ClearHTTPCache empties the HTTP cache of every context, the on-disk one included.

func (*Engine) Close

func (e *Engine) Close() error

func (*Engine) CloseTab

func (e *Engine) CloseTab(id string) error

func (*Engine) Context

func (e *Engine) Context() context.Context

func (*Engine) DefaultContext

func (e *Engine) DefaultContext() *BrowserContext

DefaultContext returns the implicit context every bare engine has.

func (*Engine) DropMemoryCache

func (e *Engine) DropMemoryCache()

DropMemoryCache forgets the in-memory tier of the HTTP cache after writing out what is queued for disk, so the next requests are served from the on-disk cache only: the state of a browser that was just restarted.

func (*Engine) ListContexts

func (e *Engine) ListContexts() []string

ListContexts names every live context (Playwright browser.contexts()).

func (*Engine) ListTabs

func (e *Engine) ListTabs() []*Tab

func (*Engine) LookupContext

func (e *Engine) LookupContext(name string) (*BrowserContext, bool)

func (*Engine) NewContext

func (e *Engine) NewContext(name string, opts ContextOptions) *BrowserContext

NewContext creates an isolated browsing context inside the engine.

func (*Engine) NewTab

func (e *Engine) NewTab(url string) (*Tab, error)

NewTab creates a blank tab. Cost target: < 2 MiB resident.

func (*Engine) NewTabInContext

func (e *Engine) NewTabInContext(c *BrowserContext, url string) (*Tab, error)

NewTabInContext creates a tab bound to a specific BrowserContext; tabs inherit the context's UA/viewport/cookies and register with its tab list.

func (*Engine) Opts

func (e *Engine) Opts() Options

func (*Engine) SetAcceptLanguage

func (e *Engine) SetAcceptLanguage(v string)

SetAcceptLanguage sets the Accept-Language value of every request the engine makes unless a context overrides it (ContextOptions.AcceptLanguage). Embedders call it from their language setting.

func (*Engine) SetFrameReadFilter

func (e *Engine) SetFrameReadFilter(f func(frameURL string) bool)

SetFrameReadFilter sets a predicate that decides, per frame document URL, whether the snapshot may include the frame and refs may act inside it. The desktop app uses it so that an embedded page the person did not allow the agent to read stays unread even when the page that embeds it is allowed. nil allows every frame.

func (*Engine) SetPopupHandler

func (e *Engine) SetPopupHandler(f func(PopupRequest))

SetPopupHandler registers the embedder's handler for windows created by page script. The Popup tab already exists (about:blank, opener linked); the handler must show it and start its navigation to req.URL (or call Popup.Navigate). Without a handler the engine navigates the popup itself in the background (CLI, tests).

func (*Engine) SetWindowCloseHandler

func (e *Engine) SetWindowCloseHandler(f func(*Tab))

SetWindowCloseHandler registers what happens when script calls window.close() on a tab it may close: the embedder should close the tab. Without a handler the engine closes it.

func (*Engine) SetWindowFocusHandler

func (e *Engine) SetWindowFocusHandler(f func(*Tab))

SetWindowFocusHandler registers what happens when script calls focus() on a popup.

func (*Engine) Tab

func (e *Engine) Tab(id string) (*Tab, error)

func (*Engine) WireTotals

func (e *Engine) WireTotals() (in, out int64)

WireTotals returns the socket totals of every context since the engine started (closed contexts included).

type Event

type Event struct {
	SID  int64     `json:"sid"`
	Tab  string    `json:"tab"`
	Kind EventKind `json:"kind"`
	At   time.Time `json:"at"`
	Data any       `json:"data,omitempty"`
}

Event is one broadcast entry. Ring buffers store these verbatim so history queries are O(n) over a bounded window, never unbounded.

type EventKind

type EventKind string

EventKind enumerates everything SDKs/MCP can subscribe to.

const (
	EvNavigated  EventKind = "Page.navigate"
	EvLoad       EventKind = "Page.load"
	EvDomMutated EventKind = "DOM.nodeInserted"
	EvConsole    EventKind = "Log.entry"
	EvRequest    EventKind = "Network.request"
	EvResponse   EventKind = "Network.response"
	EvFailure    EventKind = "Network.failure"
	EvDialog     EventKind = "Page.javascript dialog"
	EvPopup      EventKind = "Page.popup"
	EvCrash      EventKind = "Page.crashed"
	EvDownload   EventKind = "Browser.download"
	EvBinding    EventKind = "Runtime.bindingCalled"
	EvWebSocket  EventKind = "Network.webSocket"
)
const EvAudio EventKind = "Media.audio"

EvAudio is published when a tab starts or stops making sound and when its mute state changes. Data is AudioState.

const EvClipboard EventKind = "Page.clipboard"

EvClipboard is published when a page wrote to the clipboard. Data is ClipboardWrite.

const EvData EventKind = "data"

EvData is published on the Bus (Event.Kind "data") when a tab's or a context's numbers change; throttled to 4 per second per tab. Event.Data is a DataEvent.

const EvFullscreen EventKind = "Page.fullscreen"

EvFullscreen is published when the page enters or leaves element fullscreen. Data is FullscreenState.

const EvMediaSession EventKind = "Media.session"

EvMediaSession is published when the page changes its Media Session. Data is MediaSessionInfo.

type FindResult

type FindResult struct {
	Count int
	Index int     // 0-based index of the active match, -1 when none
	Top   float64 // document y (CSS px) of the active match's line, -1 when none
	Left  float64
	H     float64
}

FindResult describes the state after a find call.

type FrameInfo

type FrameInfo struct {
	Name    string
	URL     string
	Origin  string // "" = opaque
	Blocked bool   // refused by X-Frame-Options or CSP frame-ancestors
	Sandbox bool
	Ref     string // the prefix of the refs inside the frame in a snapshot: f1, f2, ... (frames_snapshot.go)
	Tab     *Tab   // the frame's document
}

FrameInfo describes one nested browsing context.

type FrameRef

type FrameRef struct {
	Ref string
	Tab *Tab
}

FrameRefs lists the frames of the document (direct children) with the ref prefix their snapshot refs carry.

type FullscreenState

type FullscreenState struct {
	Active bool `json:"active"`
}

FullscreenState is the payload of EvFullscreen and the result of Tab.Fullscreen.

type Jar

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

Jar is a small RFC-6265-flavoured cookie store shared by one BrowserContext. Capped at 1024 entries with coarse LRU eviction — bounded memory again. The unpartitioned jar and one jar per top-level site (the partitions) live side by side; a request reads the ones its context allows (see Header).

func NewJar

func NewJar() *Jar

func (*Jar) All

func (j *Jar) All(_ string) []*Cookie

All returns every stored cookie of every partition (unsorted).

func (*Jar) Attach

func (j *Jar) Attach(tr *http.Transport) http.RoundTripper

Attach installs the jar onto an http.Client via a transport RoundTrip hook, bypassing net/http's own jar so we keep SameSite/expiry semantics ourselves.

func (*Jar) ForURL

func (j *Jar) ForURL(rawurl string) string

ForURL renders the Cookie header for a request URL from the unpartitioned jar ("" if none).

func (*Jar) Header

func (j *Jar) Header(rawurl string, q cookieQuery) string

Header renders the Cookie header for a request URL from the jars the query allows.

func (*Jar) Replace

func (j *Jar) Replace(list []*Cookie)

Replace swaps in a new cookie list (used by ClearCookies).

func (*Jar) Set

func (j *Jar) Set(c *Cookie)

type Locator

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

Locator is a lazy, re-resolving element handle — exactly Playwright's Locator semantics. It stores only the selector (plus optional nth), so it costs ~48 bytes and can never leak a detached node. Every action re-resolves against the live DOM, which makes agent scripts resilient to SPA re-renders without any polling code on their side.

func (*Locator) All

func (l *Locator) All() ([]*NodeInfo, error)

func (*Locator) BackendID

func (l *Locator) BackendID() (int64, error)

func (*Locator) BoundingBox

func (l *Locator) BoundingBox() ([4]int, error)

func (*Locator) Count

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

func (*Locator) Filter

func (l *Locator) Filter(hasText string) *Locator

Filter mirrors locator.filter({ hasText }) with substring matching.

func (*Locator) First

func (l *Locator) First() *Locator

First / Last mirror locator.first() / locator.last().

func (*Locator) GetAttribute

func (l *Locator) GetAttribute(k string) (string, bool, error)

func (*Locator) InnerHTML

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

func (*Locator) InnerText

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

func (*Locator) IsChecked

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

func (*Locator) IsEnabled

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

func (*Locator) IsHidden

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

func (*Locator) IsVisible

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

func (*Locator) Last

func (l *Locator) Last() *Locator

func (*Locator) Nth

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

Nth mirrors locator.nth(i). Negative counts from the end like Python.

func (*Locator) Selector

func (l *Locator) Selector() string

func (*Locator) TextContent

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

func (*Locator) WaitBackend

func (l *Locator) WaitBackend(state string, timeout time.Duration) (int64, error)

WaitBackend resolves sel via Playwright engines and waits for state before returning the backend node id (locator auto-wait used by all actions).

func (*Locator) WaitForCondition

func (l *Locator) WaitForCondition(kind string, timeout time.Duration) error

WaitForCondition polls the DOM predicate until true or timeout. Polling is cheap because predicates are pure tree walks; interval scales with budget so a 1-core box isn't spammed. Returns last error text on timeout.

type MediaActivity

type MediaActivity struct {
	Sessions []MediaSession
}

MediaActivity is the live capture state of a tab.

func (MediaActivity) Count

func (a MediaActivity) Count(kind string) int

Count returns the number of live sessions of a kind.

type MediaArtwork

type MediaArtwork struct {
	Src   string `json:"src"`
	Sizes string `json:"sizes,omitempty"`
	Type  string `json:"type,omitempty"`
}

MediaArtwork is one image of the session's metadata.

type MediaBroker

type MediaBroker interface {
	// MediaPermission returns the stored decision for an origin: "granted", "denied" or "prompt".
	MediaPermission(t *Tab, origin, name string) string
	// RequestMedia asks the user. It blocks until the user answers or ctx is cancelled (the page went away).
	RequestMedia(ctx context.Context, r MediaRequest) MediaDecision
	// DisplaySources lists what getDisplayMedia may share from this tab's window: the tab itself, the other tabs
	// and the browser window.
	DisplaySources(t *Tab) []DisplaySource
	// OpenDisplay returns a video source for a display source id and the surface's native size.
	OpenDisplay(t *Tab, sourceID string) (capture.VideoSource, DisplayInfo, error)
	// IDSalt is the secret mixed into the per-origin device ids. It must be stable across restarts.
	IDSalt(t *Tab) string
	// MediaChanged reports the live capture sessions of a tab after every change (may be called from any goroutine).
	MediaChanged(t *Tab, act MediaActivity)
}

MediaBroker is implemented by the application that embeds the engine.

type MediaDecision

type MediaDecision struct {
	Allow     bool
	Dismissed bool   // closed without choosing (reported as "Permission dismissed")
	VideoID   string // chosen camera (a real device id), "" = the solver's pick
	AudioID   string
	SourceID  string // chosen display source
}

MediaDecision is the user's answer.

type MediaRequest

type MediaRequest struct {
	Tab    *Tab
	Origin string
	URL    string
	// Video and Audio say which kinds the page asked for; the device lists hold the candidates that satisfy the
	// constraints (the solver's pick first) so the prompt can offer a choice.
	Video, Audio               bool
	VideoDevices, AudioDevices []capture.DeviceInfo
	// Display requests: the sources to choose from and the page's hints.
	Display          bool
	Sources          []DisplaySource
	PreferCurrentTab bool
	WantAudio        bool
	Surface          string // the page's displaySurface hint: "browser", "window" or ""
}

MediaRequest is what the prompt shows.

type MediaSession

type MediaSession struct {
	ID      string
	Kind    string // "camera", "microphone" or "screen"
	Label   string
	Surface string
}

MediaSession is one live capture track.

type MediaSessionInfo

type MediaSessionInfo struct {
	Active        bool           `json:"active"` // the page set metadata, a playback state or an action handler
	Title         string         `json:"title,omitempty"`
	Artist        string         `json:"artist,omitempty"`
	Album         string         `json:"album,omitempty"`
	Artwork       []MediaArtwork `json:"artwork,omitempty"`
	PlaybackState string         `json:"playbackState"` // none | paused | playing
	Actions       []string       `json:"actions,omitempty"`
	Duration      float64        `json:"duration,omitempty"`
	Position      float64        `json:"position,omitempty"`
	Rate          float64        `json:"rate,omitempty"`
}

MediaSessionInfo is the payload of EvMediaSession and the result of Tab.MediaSession.

type MemoryClipboard

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

MemoryClipboard is a Clipboard that lives in the process: the default of a BrowserContext, and what the tests use.

func (*MemoryClipboard) Read

func (m *MemoryClipboard) Read() ([]ClipboardEntry, error)

Read implements Clipboard.

func (*MemoryClipboard) Write

func (m *MemoryClipboard) Write(es []ClipboardEntry) error

Write implements Clipboard.

type Metrics

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

Metrics is the tiny resource governor. It samples Go runtime memory and, past the soft RSS budget, forces GC + ring-buffer eviction so a runaway agent cannot OOM a 50 MB box. Cost: one goroutine waking every few seconds.

func NewMetrics

func NewMetrics(maxRSSMiB int) *Metrics

func (*Metrics) Sample

func (m *Metrics) Sample() bool

Sample records current heap+stack in-use MiB. Returns true when over budget.

func (*Metrics) Snapshot

func (m *Metrics) Snapshot() map[string]any

type NetEntry

type NetEntry struct {
	ID          int64             `json:"id"`
	Nav         int64             `json:"nav"` // navigation number: it grows with every top-level document request
	Method      string            `json:"method"`
	URL         string            `json:"url"`
	FinalURL    string            `json:"finalUrl,omitempty"`
	Type        string            `json:"type"` // document|script|style|image|font|media|xhr|frame|websocket|other
	Status      int               `json:"status"`
	StartMs     int64             `json:"start"` // unix ms
	DurMs       int64             `json:"dur"`   // -1 while pending
	Transfer    int64             `json:"transfer"`
	BodySize    int64             `json:"size"`
	MIME        string            `json:"mime,omitempty"`
	Cache       string            `json:"cache,omitempty"` // the x-sweef-cache value: hit, revalidated, miss: no-store, ...
	Blocked     bool              `json:"blocked,omitempty"`
	Reason      string            `json:"reason,omitempty"` // why it was blocked
	Error       string            `json:"error,omitempty"`
	Pending     bool              `json:"pending,omitempty"`
	ReqHeaders  map[string]string `json:"reqHeaders,omitempty"`
	RespHeaders map[string]string `json:"respHeaders,omitempty"`
	PostData    string            `json:"postData,omitempty"`
	HasBody     bool              `json:"hasBody,omitempty"`
	Truncated   bool              `json:"truncated,omitempty"`
}

NetEntry is one recorded request. Bodies are not part of the value; see Tab.DevNetBody.

type NodeInfo

type NodeInfo struct {
	NodeID    int64             `json:"nodeId"`
	BackendID int64             `json:"backendNodeId"`
	Name      string            `json:"name"`         // tag name, lowercased
	ID        string            `json:"id,omitempty"` // id attribute
	Type      string            `json:"type,omitempty"`
	Role      string            `json:"role,omitempty"`
	Text      string            `json:"text,omitempty"` // accessible-ish label
	Href      string            `json:"href,omitempty"`
	Attrs     map[string]string `json:"attrs,omitempty"`
	Visible   bool              `json:"visible"`
	Disabled  bool              `json:"disabled"`
	Checked   bool              `json:"checked,omitempty"`
	Box       [4]int            `json:"box,omitempty"` // x,y,w,h in layout px (approx)
	Focusable bool              `json:"focusable"`
}

NodeInfo is the serialisable handle the outside world uses to address DOM nodes. BackendNodeID is stable for the lifetime of the document tree.

type NoteInfo

type NoteInfo struct {
	ID, Origin, Title, Body, Tag string
	Persistent                   bool
}

Notifications lists the notifications that are currently shown (for tests and the app's notification list).

type Options

type Options struct {
	MaxRSSMiB        int  // soft resident-memory budget (memgov.go): GC pressure, ring trimming and memory returned to the OS above it
	MaxCacheMiB      int  // HTTP memory cache ceiling (default 32)
	DiskCacheMiB     int  // profile-level on-disk HTTP cache cap under CacheDir/http (0 = 100, negative = memory only)
	Headless         bool // always true today; "headful" streams to a thin client
	DisableJS        bool // pure fetch+DOM mode for tiny agents
	ConsoleRingSize  int  // console messages retained per tab
	NetworkRingSize  int  // network events retained per tab
	StateRingSize    int  // actionability/state log entries retained
	DefaultUserAgent string
	ProxyURL         string // HTTP/HTTPS/SOCKS5 proxy for every context ("" = HTTPS_PROXY/HTTP_PROXY/NO_PROXY from the environment, "direct" = none)
	AcceptLanguage   string // Accept-Language of every request (default "en-US,en;q=0.9"); see Engine.SetAcceptLanguage
	ViewportWidth    int    // default viewport width (px) for text rendering
	ViewportHeight   int    // default viewport height (px)
	SettleMs         int    // event-loop budget after actions (default 1500; an action settles for a third of it)
	NavSettleMs      int    // event-loop budget of a headless load: half before the load event, all after (default 600, at most SettleMs)
	SettleQuietMs    int    // a headless settle ends early once only timers are left and the document has not changed for this long (0 = default 300; negative = off, pump to SettleMs)
	NavQuietMs       int    // quiet window of a headless navigation's pre-load and settle pumps: they end once only timers are left and the document has not changed for this long (0 = SettleQuietMs, the library default; > 0 also caps the pre-load pump's window at 10 ms)
	NavPostLoadMs    int    // event-loop budget of a headless load after the load event (0 = NavSettleMs); the page goes on in the background pump and the next command's settle
	JSMemoryMiB      int    // QuickJS heap cap per tab (default 256: YouTube's player and its BotGuard script need more than 64)
	JSTimeoutMs      int    // single-eval timeout; a looping script is interrupted (default 30000: a real page's longest tasks, YouTube's first render among them, run past 5 s on a loaded machine, and an interrupted task leaves the page half-built)
	WarmVMs          int    // JS VMs kept pre-built so navigations skip prelude setup (default 1)
	DownloadsDir     string // where downloads are saved (default $TMPDIR/sweef-downloads)
	CacheDir         string // on-disk bytecode cache ("" = $SWEEF_CACHE_DIR or user cache dir; "off" disables)
	StorageDir       string // profile storage root of the default context: IndexedDB, Cache Storage, service workers ("" = memory only; other contexts: ContextOptions.StorageDir)
	StorageQuotaMiB  int    // hard cap per origin for all site storage in MiB (0 = 20% of the budget)
	StorageBudgetMiB int    // global budget of all origins in MiB (0 = 60% of the profile volume's free space, at most 64 GiB); see docs/storage.md
	DisableFrames    bool   // do not load <iframe> documents (frames.go): pages see no content window, as before frames existed
	BlockTrackers    bool   // refuse third-party requests to known ad, analytics and tracking hosts (trackers.go); the agent-facing commands turn it on
	HideScrollbars   bool   // lay out and paint without scrollbars, as headless Chromium under Playwright/CDP does; the agent-facing commands turn it on
	NoAutoplay       bool   // media do not preload or autoplay (the page's own play() still loads them), as under the Data Saver; the agent-facing commands turn it on: a background video cost ~150 MB of decoded frames and a core of CPU for nothing an agent reads
}

Options tune the whole browser instance for low-memory machines.

func DefaultOptions

func DefaultOptions() Options

type PWA

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

PWA is what the application uses to tell the engine about changes, and to inspect what it holds.

func (*PWA) Badge

func (p *PWA) Badge(origin string) Badge

Badge returns the app badge of an origin.

func (*PWA) Badges

func (p *PWA) Badges() map[string]Badge

Badges returns every origin that has a badge.

func (*PWA) ClearOrigin

func (p *PWA) ClearOrigin(origin string)

ClearOrigin forgets what the engine holds for origin: push subscriptions (unregistered at the service), background sync registrations, the badge, shown notifications. "Clear browsing data" calls it.

func (*PWA) Notifications

func (p *PWA) Notifications() []NoteInfo

Notifications returns what is shown now.

func (*PWA) PermissionChanged

func (p *PWA) PermissionChanged(origin string)

PermissionChanged tells open pages and workers of origin ("" = all) that a permission changed, so Notification.permission, PermissionStatus.onchange and the push permission state follow.

func (*PWA) PushServiceChanged

func (p *PWA) PushServiceChanged()

PushServiceChanged applies a new push service address (the setting changed while the browser runs): the connection to the old service is closed and, if subscriptions exist, replaced by one to the new service, which makes the old subscriptions invalid (each worker gets pushsubscriptionchange).

func (*PWA) PushServiceConfigured

func (p *PWA) PushServiceConfigured() bool

PushServiceConfigured reports whether subscribe() can work.

func (*PWA) SetOnline

func (p *PWA) SetOnline(on bool)

SetOnline sets connectivity: pending background syncs fire when it comes back, pages get online/offline events.

type PWAClock

type PWAClock interface {
	Now() time.Time
	// AfterFunc calls f once after d on its own goroutine (a fake clock may call it synchronously from Advance,
	// so f must not block) and returns a function that cancels it.
	AfterFunc(d time.Duration, f func()) (stop func() bool)
}

PWAClock abstracts time for the schedulers so tests can control it.

type PWAOptions

type PWAOptions struct {
	// Sink shows notifications. Nil: notifications cannot be shown (permission is still reported honestly).
	Sink notify.Sink
	// Permission reports "granted", "denied" or "prompt" for an origin and one of the Perm* names. Nil: "denied".
	Permission func(origin, name string) string
	// Request asks the user and returns the new state ("granted", "denied", or "prompt" when the user dismissed
	// the question). It runs on its own goroutine and may block until the user answers. Nil: nothing can be asked.
	Request func(ctx context.Context, r PermissionRequest) string
	// OpenWindow opens url in a new tab and returns it (clients.openWindow). Nil: openWindow rejects.
	OpenWindow func(url string) (*Tab, error)
	// FocusTab brings a tab to the front (WindowClient.focus, notification clicks).
	FocusTab func(*Tab)
	// NavigateTab navigates a tab (WindowClient.navigate); nil uses Tab.Navigate.
	NavigateTab func(t *Tab, url string) error
	// TabState reports whether a tab is the visible one and has focus (WindowClient.visibilityState / focused).
	TabState func(*Tab) (visible, focused bool)
	// DoNotDisturb, when it returns true, keeps notifications from being shown: the API behaves as if they were.
	DoNotDisturb func() bool
	// OnBadge is told when an origin's app badge changes.
	OnBadge func(origin string, b Badge)
	// Online reports connectivity; nil means online. SetOnline on the context can also be used.
	Online func() bool

	// PushService is the autopush service address (ws://, wss://, http:// or https://; http maps to ws). Empty:
	// the SWEEF_PUSH_SERVICE environment variable; still empty: push is unavailable and subscribe() rejects
	// with AbortError("Registration failed - push service not available").
	PushService string
	// PushServiceFunc, when set, is asked for the address each time (a setting that can change while the browser runs).
	// It takes precedence over PushService; PushServiceChanged applies a change.
	PushServiceFunc func() string
	// PushTransport replaces the autopush client (another service, or a test double).
	PushTransport func(h webpush.Handler, uaid string) (webpush.Transport, error)

	Clock           PWAClock
	Sync            SyncPolicy
	SilentPushGrace time.Duration // how long a push event may go without a notification (5 seconds)
	EventTimeout    time.Duration // how long push and notification events may run (30 seconds)
	Logf            func(format string, args ...any)
}

PWAOptions connects a BrowserContext to the application around it.

type PaintInfo

type PaintInfo struct {
	Layout, Raster time.Duration // style + layout + display list, then rasterisation
	Incremental    bool
	Rect           image.Rectangle // the part of the surface the returned image covers
}

PaintInfo describes the last PaintRGBAOpts of a tab.

type PaintOptions

type PaintOptions struct {
	Width, Height  int     // CSS px; Height <= 0 uses the tab viewport height
	DSF            float64 // device pixel ratio
	Full           bool    // paint the whole document height (capped at 16000 CSS px)
	Transparent    bool    // leave the canvas transparent (premultiplied alpha), for overlays
	KeepScrollbars bool    // keep the page's own scrollbars (default: removed; the GUI draws its own)
	// Incremental repaints only what changed since the previous incremental
	// paint of this tab (see incremental.go); the result is then the damaged
	// sub-rectangle of the surface unless the whole surface had to be repainted.
	Incremental bool
	// ScrollY paints the document scrolled by this many CSS px (used for frame
	// documents, which scroll inside their box; the GUI scrolls top-level pages
	// by moving a taller texture).
	ScrollY int
	// Cull drops the ops that cannot put ink in the rows [ScrollY, ScrollY+Height) before rasterising, so painting a
	// band of a very tall page does not cost more than painting the top of it.
	Cull bool
}

PaintOptions selects how PaintRGBAOpts rasterises.

type PartitionPolicy

type PartitionPolicy struct {
	Cookies CookieMode
	// Exception, when set, is asked for every third-party cookie decision with the top-level site and the site of
	// the request or document; returning true gives that pair unpartitioned cookie access (the first-party jar).
	// It runs on the request path and must be fast and safe for concurrent use.
	Exception func(topSite, embeddedSite string) bool
	// StorageAccess decides document.requestStorageAccess() from a third-party document: it is told the two
	// sites and whether the person has interacted with embeddedSite as a top-level page in this context.
	// nil = grant exactly when they have (the interaction heuristic of Safari and Firefox).
	StorageAccess func(topSite, embeddedSite string, interacted bool) bool
}

PartitionPolicy is the cookie policy of a browsing context.

type PermissionRequest

type PermissionRequest struct {
	Origin     string
	Permission string // PermNotifications or PermPush
	TabID      string
	Gesture    bool // the page had a user gesture shortly before asking
}

PermissionRequest is a question to the user.

type PlayerStats

type PlayerStats struct {
	Total, Dropped, Corrupted int64
}

PlayerStats are the counters behind getVideoPlaybackQuality().

type PopupEvent

type PopupEvent struct {
	Opener  string    `json:"opener"`
	Popup   string    `json:"popup,omitempty"`
	URL     string    `json:"url"`
	Name    string    `json:"name,omitempty"`
	Blocked bool      `json:"blocked"`
	Reason  string    `json:"reason,omitempty"` // no user activation | sandbox | scheme
	At      time.Time `json:"at"`
}

PopupEvent is one window.open / target=_blank decision, allowed or not.

type PopupRequest

type PopupRequest struct {
	Opener, Popup *Tab
	URL           string // absolute, "about:blank" for window.open("")
	Name          string
	Features      string
	Referer       string
	NoOpener      bool
	Post          func(dest *Tab) error // non-nil for a form submitted with method=post to a new window
}

PopupRequest is handed to the embedder's popup handler once the Popup tab exists.

type RTCTrackDesc

type RTCTrackDesc struct {
	ID        string  `json:"id"`
	Kind      string  `json:"kind"`
	DeviceID  string  `json:"deviceId"`
	Label     string  `json:"label"`
	Width     int     `json:"width"`
	Height    int     `json:"height"`
	FrameRate float64 `json:"frameRate"`
	Canvas    int64   `json:"canvas"` // node id of the canvas behind canvas.captureStream()
	Enabled   bool    `json:"enabled"`
	// voice processing the track asks for (its settings): nil when the page's track says nothing
	EchoCancellation *bool `json:"echoCancellation"`
	NoiseSuppression *bool `json:"noiseSuppression"`
	AutoGainControl  *bool `json:"autoGainControl"`
}

RTCTrackDesc describes a page track as the engine sees it when it is attached to a sender.

type RTCTrackSource

type RTCTrackSource struct {
	OpenVideo func(c capture.VideoConstraints) (capture.VideoSource, error)
	OpenAudio func(c capture.AudioConstraints) (capture.AudioSource, error)
}

RTCTrackSource opens fresh capture sources for one track (a sender needs its own instance, because a capture.VideoSource can only be started once).

type Ring

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

Ring is a fixed-capacity circular buffer of events. Bounded memory is the whole point: an agent that never reads logs still cannot OOM the browser.

func NewRing

func NewRing(size int) *Ring

func (*Ring) All

func (r *Ring) All() []Event

func (*Ring) Push

func (r *Ring) Push(e Event) Event

func (*Ring) Seq

func (r *Ring) Seq() int64

Seq is the SID of the newest entry (0 for none).

func (*Ring) Since

func (r *Ring) Since(sinceSID int64) []Event

Since returns all events with SID > sinceSID, oldest first.

func (*Ring) Trim

func (r *Ring) Trim()

Trim halves the live window — called by the memory governor under pressure.

type RouteRule

type RouteRule struct {
	Pattern      string            `json:"pattern"`
	Method       string            `json:"method,omitempty"`
	BodyContains string            `json:"bodyContains,omitempty"`
	Action       string            `json:"action"` // fulfill | abort | continue
	Status       int               `json:"status,omitempty"`
	Body         string            `json:"body,omitempty"`
	ContentType  string            `json:"contentType,omitempty"`
	Headers      map[string]string `json:"headers,omitempty"` // fulfill: response headers; continue: request headers to set
	URL          string            `json:"url,omitempty"`     // continue: rewrite URL
	NewMethod    string            `json:"newMethod,omitempty"`
	NewBody      *string           `json:"newBody,omitempty"`
	Times        int               `json:"times,omitempty"`
	Hits         int               `json:"hits"`
	// contains filtered or unexported fields
}

RouteRule is one interception rule (Playwright page.route semantics): match by URL glob (or /regex/), optional method and request-body substring, then fulfill with a canned response, abort, or continue with modifications. Times > 0 removes the rule after that many hits.

type SaverLevel

type SaverLevel int

SaverLevel is the coarse Data Saver setting.

const (
	SaverOff SaverLevel = iota
	SaverStandard
	SaverStrict
)

func ParseSaverLevel

func ParseSaverLevel(s string) SaverLevel

ParseSaverLevel maps "off" | "standard" | "strict" to a level (off for anything else).

func (SaverLevel) String

func (l SaverLevel) String() string

type ScrollRequest

type ScrollRequest struct {
	X, Y   float64 // the document offset to scroll to, CSS px, already within the scrollable range
	Smooth bool    // behavior: smooth, or scroll-behavior: smooth on the root element
}

ScrollRequest is page script asking the window to scroll the viewport.

type ScrollTarget

type ScrollTarget struct {
	ID         int64      // backend id of the element
	X, Y       float64    // how far its content is scrolled, CSS px
	MaxX, MaxY float64    // the scrollable range
	Rect       [4]float64 // border box in document CSS px (x, y, w, h)
	SmoothCSS  bool       // scroll-behavior: smooth
	Hidden     bool       // overflow: hidden (scrollable by script only)
}

ScrollTarget describes one scroll container.

type SelInfo

type SelInfo struct {
	Has                 bool
	AnchorID, FocusID   int64
	AnchorOff, FocusOff int
}

SelInfo is the document selection as script sees it.

type ServiceWorkerInfo

type ServiceWorkerInfo struct {
	Scope      string
	ScriptURL  string
	Installing string // state of the installing worker, "" when none
	Waiting    string
	Active     string
}

ServiceWorkerInfo describes one registration.

type SkippedItem

type SkippedItem struct {
	NodeID int64 // backend node id of the placeholder element (0 for resources without one)
	Kind   DataKind
	URL    string
	Bytes  int64  // size when known (Content-Length or cache), else -1
	Reason string // "strict", "too-large", "third-party", "script-budget", "frame", "background"
}

SkippedItem describes one resource the policy withheld on this page.

type SnapshotOptions

type SnapshotOptions = fnet.SnapshotOptions

SnapshotOptions mirrors net.SnapshotOptions for callers outside the engine.

type Source

type Source struct {
	Key    string `json:"key"`  // handle for DevSource: "net:<id>" or "inline:<n>"
	URL    string `json:"url"`  // address, or "(inline script)" / "(inline style)"
	Kind   string `json:"kind"` // script | style | document
	Size   int64  `json:"size"`
	Inline bool   `json:"inline,omitempty"`
	Nav    int64  `json:"nav"`
	// Missing: the address is linked by the page but its text was not recorded (it was blocked or failed).
	Missing bool   `json:"missing,omitempty"`
	Status  int    `json:"status,omitempty"`
	Error   string `json:"error,omitempty"`
}

Source is one script or stylesheet of the page, for the Sources panel.

type SyncPolicy

type SyncPolicy struct {
	MaxAttempts   int           // attempts before a registration is dropped (3)
	InitialDelay  time.Duration // wait after the first failure (5 minutes)
	DelayFactor   float64       // growth of the wait per failure (3)
	PeriodicFloor time.Duration // least interval between two periodicsync events of an origin (12 hours)
	EventTimeout  time.Duration // how long a sync event may run (5 minutes)
}

SyncPolicy tunes Background Sync; the zero value is Chromium's.

type Tab

type Tab struct {
	ID string
	// contains filtered or unexported fields
}

Tab is one browsing context. Goroutine-light: no dedicated thread, just state + a mutex; JS evaluation happens on demand.

func (*Tab) AddInitScript

func (t *Tab) AddInitScript(src string) string

func (*Tab) AddRoute

func (t *Tab) AddRoute(r *RouteRule) error

AddRoute installs a rule; later rules take precedence, as in Playwright.

func (*Tab) AgentLoading

func (t *Tab) AgentLoading() bool

AgentLoading reports whether the tab is in agent loading mode.

func (*Tab) AriaSnapshotV2

func (t *Tab) AriaSnapshotV2(o SnapshotOptions) (string, error)

AriaSnapshotV2 renders the Playwright-format accessibility tree with options.

func (*Tab) AriaSnapshotYAML

func (t *Tab) AriaSnapshotYAML() (string, error)

AriaSnapshotYAML returns the Playwright-style YAML accessibility tree of the page. Every node carries [ref=eN] — the stable backend node id — which agents can pass back to any action as selector "eN" (see ResolveEngine ref support).

func (*Tab) ArmDialogResponse

func (t *Tab) ArmDialogResponse(accept bool, promptText string)

func (*Tab) AttributesByBackend

func (t *Tab) AttributesByBackend(backendID int64) map[string]string

AttributesByBackend returns every attribute of a node as a flat map.

func (*Tab) AudioState

func (t *Tab) AudioState() AudioState

AudioState reports whether the tab is audible and whether it is muted.

func (*Tab) BindingCalls

func (t *Tab) BindingCalls(sinceSID int64) []BindingCall

BindingCalls returns calls recorded after sinceSID.

func (*Tab) Bindings

func (t *Tab) Bindings() []string

func (*Tab) BitmapSourceFor

func (t *Tab) BitmapSourceFor(n *html.Node) BitmapSource

BitmapSourceFor returns the registered source for a node, or nil.

func (*Tab) BlockedPopups

func (t *Tab) BlockedPopups() []PopupEvent

BlockedPopups lists the popups the blocker refused in this tab.

func (*Tab) ByRef

func (t *Tab) ByRef(ref string) (*NodeInfo, error)

ByRef resolves a snapshot ref like "e42" or "backend://e42" to its Info.

func (*Tab) CaptureSessions

func (t *Tab) CaptureSessions() []MediaSession

CaptureSessions lists the live capture tracks of the current document.

func (*Tab) CaretMove

func (t *Tab) CaretMove(id int64, off int, dir string) (nid int64, noff int, ok bool)

CaretMove computes where the caret or the selection's focus goes from (node id, offset in UTF-16 units; for a text control the offset is into its value) when moved by dir: "left", "right", "wordleft", "wordright", "up", "down", "linestart", "lineend", "docstart", "docend", "pageup", "pagedown". It returns the new node id and offset, and ok false when the caret cannot move that way.

func (*Tab) CaretRect

func (t *Tab) CaretRect(id int64, off int) (r [4]float64, ok bool)

CaretRect is the rectangle of the caret at a text boundary (document coordinates).

func (*Tab) Check

func (t *Tab) Check(sel string) error

Check / Uncheck toggle checkbox-or-radio semantics.

func (*Tab) Click

func (t *Tab) Click(sel string) error

Click resolves sel (Playwright engines supported), scrolls it into view, dispatches pointer/mouse/click events into JS, then applies navigation semantics: <a href> navigates, submit buttons post their form, labels focus their control.

func (*Tab) ColorSchemeName

func (t *Tab) ColorSchemeName() string

func (*Tab) ConsoleLog

func (t *Tab) ConsoleLog(sinceSID int64) []Event

func (*Tab) Context

func (t *Tab) Context() *BrowserContext

Context returns the tab's browser context (creating the default lazily).

func (*Tab) CrossOriginIsolated

func (t *Tab) CrossOriginIsolated() bool

CrossOriginIsolated reports whether the current document is cross-origin isolated.

func (*Tab) CtlSelGet

func (t *Tab) CtlSelGet(id int64) (start, end, dir int, ok bool)

CtlSelGet returns the selection of the text control with backend id, in UTF-16 units of its value, and its direction (1 forward, -1 backward, 0 none). ok is false while the control has never had one.

func (*Tab) CtlSelSet

func (t *Tab) CtlSelSet(id int64, start, end, dir int)

CtlSelSet sets the selection of a text control.

func (*Tab) DataStats

func (t *Tab) DataStats() DataStats

DataStats returns this tab's numbers since its last navigation. WireIn and WireOut are the sums of the attributed exchanges (approximate); the exact socket totals live on the BrowserContext.

func (*Tab) DevAttach

func (t *Tab) DevAttach(on bool)

DevAttach marks Developer Tools as open (or closed) for the tab: while open, bodies of text responses and images are kept for the Network panel's preview. Closing drops those bodies.

func (*Tab) DevClearNetwork

func (t *Tab) DevClearNetwork()

DevClearNetwork forgets the recorded requests.

func (*Tab) DevCookies

func (t *Tab) DevCookies() []DevCookie

DevCookies lists the cookies of the tab's context that apply to its current URL (the httpOnly ones too: this is the person's own browser, and the page cannot see this list).

func (*Tab) DevDOMChildren

func (t *Tab) DevDOMChildren(id int64, depth int) ([]DOMNode, error)

DevDOMChildren returns the children of a node, depth levels deep (0: just the children).

func (*Tab) DevDOMNode

func (t *Tab) DevDOMNode(id int64) (DOMNode, error)

DevDOMNode returns one node with its attributes (no children).

func (*Tab) DevDOMPath

func (t *Tab) DevDOMPath(id int64) ([]int64, error)

DevDOMPath returns the ids from the document down to the node, so the panel can expand to it.

func (*Tab) DevDOMRoot

func (t *Tab) DevDOMRoot() (DOMNode, error)

DevDOMRoot returns the document with its first levels expanded (down to <body>'s children).

func (*Tab) DevEval

func (t *Tab) DevEval(expr string) (DevEvalResult, error)

DevEval evaluates a Console expression in the page and describes the result. Errors the expression throws are part of the result, not Go errors.

func (*Tab) DevHighlight

func (t *Tab) DevHighlight(id int64) bool

DevHighlight marks an element on the page with the box-model overlay (0 clears it) and reports whether it changed. The overlay is drawn into the page's display list by PaintRGBAOpts; it is never part of the document.

func (*Tab) DevNav

func (t *Tab) DevNav() int64

DevNav is the number of the tab's current navigation as the recorder counts them.

func (*Tab) DevNetBody

func (t *Tab) DevNetBody(id int64) (body []byte, e NetEntry, ok bool)

DevNetBody returns a stored response body. ok is false when none is stored (never kept, evicted, or the response had no body).

func (*Tab) DevNetEntry

func (t *Tab) DevNetEntry(id int64) (NetEntry, bool)

DevNetEntry returns one recorded request.

func (*Tab) DevNetUpdates

func (t *Tab) DevNetUpdates(sinceID int64, pending []int64) []NetEntry

DevNetUpdates returns the entries that changed since the caller last looked: new ones and ones that were pending at sinceID. The caller passes the highest ID it has and the IDs it still sees pending.

func (*Tab) DevNetwork

func (t *Tab) DevNetwork(sinceID int64) []NetEntry

DevNetwork returns the recorded requests newer than sinceID (0 = all), oldest first. Bodies are left out.

func (*Tab) DevNodeAt

func (t *Tab) DevNodeAt(x, y int) (int64, error)

DevNodeAt returns the element at a point of the page (CSS px in the viewport), for "Inspect".

func (*Tab) DevNoteBlocked

func (t *Tab) DevNoteBlocked(rawurl, reason string)

DevNoteBlocked tells the recorder that the embedder's request filter (the tracker blocker) is about to refuse a request, so the entry that follows is shown as blocked by it.

func (*Tab) DevRemoveAttr

func (t *Tab) DevRemoveAttr(id int64, name string) error

DevRemoveAttr removes an attribute.

func (*Tab) DevRemoveNode

func (t *Tab) DevRemoveNode(id int64) error

DevRemoveNode deletes a node from the document (not the document, <html>, <head> or <body>).

func (*Tab) DevSetAttr

func (t *Tab) DevSetAttr(id int64, name, value string) error

DevSetAttr sets an attribute of an element (adds it when new).

func (*Tab) DevSetText

func (t *Tab) DevSetText(id int64, text string) error

DevSetText replaces the data of a text or comment node.

func (*Tab) DevSignals

func (t *Tab) DevSignals() DevSignals

DevSignals reads the counters.

func (*Tab) DevSource

func (t *Tab) DevSource(key string) (text string, err error)

DevSource returns the text of a source listed by DevSources.

func (*Tab) DevSources

func (t *Tab) DevSources() []Source

DevSources lists the scripts and stylesheets of the current document: what was fetched (from the recorder) and the inline <script> and <style> elements of its tree.

func (*Tab) DevStorage

func (t *Tab) DevStorage() (local, session [][2]string)

DevStorage lists the page's localStorage and sessionStorage (name, value), for the Application panel.

func (*Tab) DevStyle

func (t *Tab) DevStyle(id int64) (DevStyle, error)

DevStyle returns the matched rules, the computed style and the box model of an element.

func (*Tab) DialogLog

func (t *Tab) DialogLog(sinceSID int64) []Event

func (*Tab) Dirty

func (t *Tab) Dirty() bool

Dirty reports whether the document changed (DOM, attributes, text, styles) since the last PaintRGBAOpts, i.e. whether a paint would produce new pixels. It is a cheap counter comparison. Always true before the first paint.

func (*Tab) DocumentCookie

func (t *Tab) DocumentCookie() string

DocumentCookie is the string document.cookie returns for the tab's document.

func (*Tab) DownloadURL

func (t *Tab) DownloadURL(rawurl, name string) (Download, error)

DownloadURL fetches a URL straight to the downloads directory (<a download>, or an agent asking for a file).

func (*Tab) Downloads

func (t *Tab) Downloads() []Download

Downloads lists files saved by this tab.

func (*Tab) Drag

func (t *Tab) Drag(source, target string) error

Drag fires dragstart/drop/dragend between two elements' centres.

func (*Tab) ElementBoxes

func (t *Tab) ElementBoxes() []fnetBoxRow

ElementBoxes returns every element's layout box in document order (all coordinates in CSS px, document space). Used by the fidelity harness and diagnostics.

func (*Tab) EndCapture

func (t *Tab) EndCapture(sessionID string)

EndCapture ends one capture session ("Stop sharing", a revoked permission). The page sees the track end.

func (*Tab) EndCaptureKind

func (t *Tab) EndCaptureKind(kind string)

EndCaptureKind ends every session of a kind ("camera", "microphone", "screen"), e.g. after the user revokes the permission in the site settings.

func (*Tab) Evaluate

func (t *Tab) Evaluate(expr string) (json.RawMessage, error)

Evaluate runs JS in the tab's VM, awaits a returned promise, and returns the JSON-encoded completion value. DOM nodes serialise as {nodeType, tagName, id, ref}.

func (*Tab) ExitFullscreen

func (t *Tab) ExitFullscreen()

ExitFullscreen leaves element fullscreen as the user did (Esc, F11, a tab switch): the page sees fullscreenchange. It is a no-op when nothing is fullscreen.

func (*Tab) ExposeBinding

func (t *Tab) ExposeBinding(name string) error

func (*Tab) ExtraHeaders

func (t *Tab) ExtraHeaders() map[string]string

func (*Tab) Fill

func (t *Tab) Fill(sel, value string) error

Fill sets a control's value with auto-wait and dispatches input/change into page JavaScript (Playwright fill semantics).

func (*Tab) Fill2

func (t *Tab) Fill2(sel, value string) error

Fill sets a value instantly (Playwright fill fast-path). Works on inputs, textareas and selects (select matches value OR visible label).

func (*Tab) FindClear

func (t *Tab) FindClear()

FindClear removes the find highlights.

func (*Tab) FindStart

func (t *Tab) FindStart(query string, fromY float64) FindResult

FindStart looks for query in the page and makes the first match at or after the top of the view active. It reports the number of matches. Empty queries clear the highlights.

func (*Tab) FindStep

func (t *Tab) FindStep(idx int) FindResult

FindStep makes match idx (wrapping around) the active one.

func (*Tab) Focus

func (t *Tab) Focus(sel string) error

Focus moves DOM focus to the element (dispatches focus/focusin).

func (*Tab) FocusFrame

func (t *Tab) FocusFrame(leaf *Tab)

FocusFrame makes leaf (this tab or one of its nested frames) the document that receives keyboard input, blurring the element of the document that had it.

func (*Tab) FocusedTab

func (t *Tab) FocusedTab() *Tab

FocusedTab is the document that has keyboard focus: t, or a nested frame.

func (*Tab) FontsPending

func (t *Tab) FontsPending() int

FontsPending is the number of web fonts the page's text asked for that are still downloading (a window that waits for a settled page, such as a headless screenshot, treats the tab as busy while it is above zero).

func (*Tab) Frame

func (t *Tab) Frame(o PaintOptions, settle time.Duration) (img *image.RGBA, painted, ok bool)

Frame is the one call that turns the page's pending work into a frame: it runs the page's timers, microtasks and animation callbacks once (settle is the time budget, as for Settle), and paints only if the document changed since the last paint, so a burst of updates that arrive before the frame is taken (a key handler and the state patch that answers it) costs one style, layout and raster. painted is false, with a nil image, when nothing changed. ok is false when the render pipeline is not active for the document.

func (*Tab) FrameByRef

func (t *Tab) FrameByRef(ref string) (*Tab, bool)

FrameByRef resolves "f1" or "f1f2" to the nested frame tab.

func (*Tab) FrameHit

func (t *Tab) FrameHit(x, y int) (leaf *Tab, lx, ly int)

FrameHit finds the document that receives a pointer event at the document point (x, y): the tab itself, or the deepest frame under the point with the point translated into its document space.

func (*Tab) FrameRefs

func (t *Tab) FrameRefs() []FrameRef

FrameRefs lists the readable child frames in tree order with their refs (f1, f2, ...).

func (*Tab) FrameTabs

func (t *Tab) FrameTabs() []*Tab

FrameTabs returns the child frames of the tab's document in document order. Each is a Tab that can be evaluated in, read and snapshotted like any other; it is not in the engine's tab list.

func (*Tab) Frames

func (t *Tab) Frames() []FrameInfo

Frames describes the child frames in document order.

func (*Tab) Fullscreen

func (t *Tab) Fullscreen() FullscreenState

Fullscreen reports whether an element of the page is fullscreen.

func (*Tab) FullyLoaded

func (t *Tab) FullyLoaded() bool

FullyLoaded reports whether LoadFully is in effect for the current page.

func (*Tab) Generation

func (t *Tab) Generation() uint64

Generation returns the document's mutation counter (0 without a document). It changes whenever the DOM or computed styles change, so a compositor can skip repainting an unchanged tab.

func (*Tab) Geolocation

func (t *Tab) Geolocation() [2]float64

func (*Tab) GetAttributeByBackend

func (t *Tab) GetAttributeByBackend(backendID int64, k string) (string, bool, error)

func (*Tab) GetStorageValue

func (t *Tab) GetStorageValue(key string) (string, bool)

GetStorageValue reads from the context store for the current origin.

func (*Tab) GoBack

func (t *Tab) GoBack() error

func (*Tab) GoForward

func (t *Tab) GoForward() error

func (*Tab) GrantPermissions

func (t *Tab) GrantPermissions(perms []string)

func (*Tab) HAR

func (t *Tab) HAR() ([]byte, error)

HAR exports the network ring in Chrome HAR 1.2 format.

func (*Tab) HTML

func (t *Tab) HTML(pretty bool) string

func (*Tab) HandleDialog

func (t *Tab) HandleDialog(d Dialog) (bool, string)

Dialogs records a JS dialog and applies the armed response like Playwright's page.on("dialog"). Returns whether it was accepted.

func (*Tab) HasTransientActivation

func (t *Tab) HasTransientActivation() bool

HasTransientActivation reports whether a user gesture happened recently enough to allow a popup.

func (*Tab) Hover

func (t *Tab) Hover(sel string) error

Hover dispatches mouseenter/mouseover on the matched element.

func (*Tab) InnerHTMLByBackend

func (t *Tab) InnerHTMLByBackend(backendID int64) string

func (*Tab) IsBackground

func (t *Tab) IsBackground() bool

IsBackground reports the last SetBackground value.

func (*Tab) IsClosed

func (t *Tab) IsClosed() bool

IsClosed reports whether the tab has been closed.

func (*Tab) IsOfflineMode

func (t *Tab) IsOfflineMode() bool

func (*Tab) Keyboard

func (t *Tab) Keyboard(keys string) error

Keyboard sends a raw key sequence to the focused element/body.

func (*Tab) KeyboardType

func (t *Tab) KeyboardType(text string, delay time.Duration) error

KeyboardType types text into the focused element one key at a time (keydown, keypress, beforeinput, input, keyup per character), like Playwright's keyboard.type.

func (*Tab) LastPaintInfo

func (t *Tab) LastPaintInfo() *PaintInfo

LastPaintInfo reports how the last PaintRGBAOpts went (nil before the first).

func (*Tab) LayoutStats

func (t *Tab) LayoutStats() (n int64, total time.Duration)

LayoutStats reports how many times the render pipeline ran style + layout + display list for this tab and how long they took in total. A layout read from page JavaScript (offsetWidth, getBoundingClientRect, ...) on a dirty tree counts here too, so the difference of two readings around an operation is the number of (forced or painting) layouts it caused.

func (*Tab) LoadFinish

func (t *Tab) LoadFinish()

LoadFinish runs a pending progressive load to its end.

func (*Tab) LoadFully

func (t *Tab) LoadFully() error

LoadFully reloads the current page once without any Data Saver policy: the document, its images, scripts and media load as if the saver were off, and stay that way (lazy scrolling included) until the tab navigates elsewhere.

func (*Tab) LoadLoaded

func (t *Tab) LoadLoaded() bool

LoadLoaded reports whether the current document's load event has fired (true also when no progressive load is pending).

func (*Tab) LoadPending

func (t *Tab) LoadPending() bool

LoadPending reports whether a progressive load still has work to do.

func (*Tab) LoadSkipped

func (t *Tab) LoadSkipped(nodeID int64) error

LoadSkipped fetches the resource behind a placeholder (an <img> or a frame marked data-sweef-lite) at full size, ignoring the caps, and swaps it in. nodeID is the backend node id of the placeholder element. Uncovering a frame placeholder starts loading the frame document.

func (*Tab) LoadSkippedImages

func (t *Tab) LoadSkippedImages() (int, error)

LoadSkippedImages loads every withheld image on the page and every deferred lazy one ("Load images on this page"). It returns how many images it loaded.

func (*Tab) LoadStep

func (t *Tab) LoadStep(slice time.Duration) (more bool, wait time.Duration)

LoadStep advances a pending progressive load for about slice. more is false when nothing is pending any more; wait is how long the caller may leave the tab alone before the next step (a timer is not due yet), 0 = step again now.

func (*Tab) LoadTimeline

func (t *Tab) LoadTimeline() []TraceMark

LoadTimeline returns a copy of the marks of the current navigation, in the order they were recorded.

func (*Tab) Locator

func (t *Tab) Locator(sel string) *Locator

func (*Tab) LogConsole

func (t *Tab) LogConsole(level, text string)

func (*Tab) MarkUserActivation

func (t *Tab) MarkUserActivation()

MarkUserActivation records a trusted user input (a click or key press delivered by the window shell). Page scripts cannot call it, which is why the application reports input here instead of the page's event handlers doing so.

func (*Tab) MediaSession

func (t *Tab) MediaSession() MediaSessionInfo

MediaSession returns what the page last published.

func (*Tab) MediaSessionAction

func (t *Tab) MediaSessionAction(action string, arg float64) bool

MediaSessionAction presses a button of the browser's media controls: the page's handler for the action runs (play, pause and seeking fall back to the page's media element). arg is the seek offset or the seekto position.

func (*Tab) MouseClick

func (t *Tab) MouseClick(x, y int) error

MouseClick hit-tests coordinates against deterministic bounding boxes and clicks whatever element covers the point.

func (*Tab) MouseDown

func (t *Tab) MouseDown(x, y int)

func (*Tab) MouseMove

func (t *Tab) MouseMove(x, y int)

func (*Tab) MouseUp

func (t *Tab) MouseUp(x, y int)

func (*Tab) MouseWheel

func (t *Tab) MouseWheel(dx, dy int) error

MouseWheel accumulates wheel deltas (agents use it to trigger lazy-loaders).

func (*Tab) Navigate

func (t *Tab) Navigate(rawurl string, headers map[string]string) error

Navigate fetches url and installs the resulting document. This is the equivalent of Playwright's page.goto with waitUntil baked in.

func (*Tab) NavigateProgressive

func (t *Tab) NavigateProgressive(rawurl string, headers map[string]string) error

NavigateProgressive is Navigate for a window that shows the page while it loads (the GUI). It returns as soon as a first frame can be painted: the document is fetched and parsed, its render-blocking stylesheets are in and the scripts that were already downloaded and are quick have run. Everything else (the remaining scripts, DOMContentLoaded, load, the settle pump, and with SetAsyncImages the images) is left pending: the caller drives it with LoadStep between paints and input, or runs it out with LoadFinish. Headless callers (CLI, RPC, MCP, the agent) use Navigate, which returns only when the page has settled.

func (*Tab) NetworkLog

func (t *Tab) NetworkLog(sinceSID int64) []Event

func (*Tab) NormalizeScroll

func (t *Tab) NormalizeScroll() bool

NormalizeScroll lays the document out and brings the scroll offsets of its containers back into range (the content shrank, a container got smaller). It reports whether anything moved, in which case the next layout differs. Worker only.

func (*Tab) NoteScrollY

func (t *Tab) NoteScrollY(y int)

NoteScrollY records the viewport's scroll offset (CSS px) so that window.scrollY and getBoundingClientRect are right at once. The window calls it for every frame of a scroll.

func (*Tab) NoteUserActivation

func (t *Tab) NoteUserActivation()

NoteUserActivation records a trusted user gesture (click, tap, key press) in this document and in the documents that embed it. Embedders call it from real input; the engine calls it for agent actions that stand in for a person.

func (*Tab) NotifyMediaPermissionChanged

func (t *Tab) NotifyMediaPermissionChanged()

NotifyMediaPermissionChanged tells the page that a stored permission changed (PermissionStatus change events).

func (*Tab) Opener

func (t *Tab) Opener() *Tab

Opener is the window that opened this one with script (nil after noopener, a COOP severing, or when the opener is gone).

func (*Tab) OriginOrNull

func (t *Tab) OriginOrNull() string

OriginOrNull is the document's origin as scripts see it ("null" when opaque).

func (*Tab) OuterHTMLByBackend

func (t *Tab) OuterHTMLByBackend(backendID int64) string

func (*Tab) PDF

func (t *Tab) PDF(o pdf.Options) ([]byte, error)

PDF renders the current page as a PDF document (Playwright page.pdf).

func (*Tab) PNGScreenshot

func (t *Tab) PNGScreenshot(width, height int, dsf float64) []byte

PNGScreenshot renders the page's flow layout (see net/layout.go) to PNG: text in a bitmap font at heading sizes, links in blue, form controls as outlined boxes with their values, images as labelled placeholders. It is a schematic of the page, not a pixel replica, but its geometry is exactly the geometry used for element boxes and coordinate clicks, so an agent can point at what it sees. width/height <= 0 use the viewport; dsf scales.

func (*Tab) PNGScreenshotFull

func (t *Tab) PNGScreenshotFull(width int, dsf float64) []byte

PNGScreenshotFull renders the whole page height (Playwright fullPage).

func (*Tab) PaintRGBA

func (t *Tab) PaintRGBA(width, height int, dsf float64, full bool) (*image.RGBA, bool)

PaintRGBA rasterises the page straight to an RGBA image (no PNG round trip) with an opaque white canvas and no page scrollbars. width/height are CSS pixels; the result is (width*dsf)x(height*dsf).

func (*Tab) PaintRGBAOpts

func (t *Tab) PaintRGBAOpts(o PaintOptions) (*image.RGBA, bool)

PaintRGBAOpts is PaintRGBA with options. ok is false when the render pipeline is not active for this document.

func (*Tab) Parent

func (t *Tab) Parent() *Tab

Parent is the embedding tab for a frame document, nil otherwise.

func (*Tab) PermissionsList

func (t *Tab) PermissionsList() []string

func (*Tab) PopupLog

func (t *Tab) PopupLog(sinceSID int64) []Event

PopupLog returns the allowed and blocked window.open decisions of this tab.

func (*Tab) PosAtPoint

func (t *Tab) PosAtPoint(x, y float64) (id int64, off int, ok bool)

PosAtPoint is the boundary point nearest to the document point (x, y) on selectable text, for caretPositionFromPoint; ok is false on a page without text.

func (*Tab) Press

func (t *Tab) Press(sel, keys string) error

Press sends one or more key presses ("Enter", "Control+a", "Tab"). Enter on a form field submits the enclosing form like real browsers do.

func (*Tab) QuerySelector

func (t *Tab) QuerySelector(sel string) (*NodeInfo, error)

func (*Tab) QuerySelectorAll

func (t *Tab) QuerySelectorAll(sel string) ([]*NodeInfo, error)

func (*Tab) QuietCount

func (t *Tab) QuietCount() uint64

QuietCount is how many quiet changes the document has had. Generation moves by one for each of them (and by more for anything else).

func (*Tab) RangeRects

func (t *Tab) RangeRects(sid int64, so int, eid int64, eo int) [][4]float64

RangeRects returns the rectangles (document coordinates, CSS px) of the text between two boundary points, one per line box, for Range.getClientRects.

func (*Tab) RectByRef

func (t *Tab) RectByRef(ref string) (r [4]float64, ok bool)

RectByRef returns the layout rectangle {x, y, w, h} (CSS px, document space) of the element a snapshot ref such as "e12" points to. The GUI uses it to place the agent's cursor; ok is false when the ref is unknown or the element has no box.

func (*Tab) Reload

func (t *Tab) Reload() error

Reload re-navigates to the current URL, bypassing cached state — like Playwright's page.reload().

func (*Tab) RemoveInitScript

func (t *Tab) RemoveInitScript(id string)

func (*Tab) RemoveRoutes

func (t *Tab) RemoveRoutes(pattern string)

RemoveRoutes drops rules with the given pattern ("" drops all).

func (*Tab) Route

func (t *Tab) Route(glob string, handler func(*http.Request) (int, string, bool))

Route installs an interception rule (glob on URL). handler may return a mock response body/status or abort the request.

func (*Tab) Routes

func (t *Tab) Routes() []RouteRule

Routes lists the active rules.

func (*Tab) RunFor

func (t *Tab) RunFor(d time.Duration)

RunFor runs the page's event loop for d (timers, animation frames, network callbacks) without the early stop of a settle: the "wait <ms>" of an agent, after which an animation or a delayed render has progressed as far as it would have in a browser.

func (*Tab) Sandboxed

func (t *Tab) Sandboxed() bool

Sandboxed reports whether the document is inside a sandboxed frame.

func (*Tab) SaveDownloadBytes

func (t *Tab) SaveDownloadBytes(name, mimeType string, data []byte, srcURL string) Download

SaveDownloadBytes stores bytes produced by page code (blob: and data: URLs).

func (*Tab) Screenshot

func (t *Tab) Screenshot(width int) string

Screenshot renders the current document as structured text — the agent-first equivalent of a screenshot (token-cheap, deterministic). width<=0 uses the context viewport width.

func (*Tab) ScriptsAllowed

func (t *Tab) ScriptsAllowed() bool

ScriptsAllowed reports whether script (including the embedder's input helper) can run in the document.

func (*Tab) ScrollFrameBy

func (t *Tab) ScrollFrameBy(dy int) bool

ScrollFrameBy scrolls a frame document by dy CSS px inside its box and reports whether it moved (false at either end, so the caller can scroll the page instead).

func (*Tab) ScrollIntoView

func (t *Tab) ScrollIntoView(sel string) error

ScrollIntoView records scroll state and dispatches scroll events.

func (*Tab) ScrollTargetAt

func (t *Tab) ScrollTargetAt(x, y, dx, dy float64) (tg ScrollTarget, found, blocked bool)

ScrollTargetAt finds the overflow container that a scroll gesture of (dx, dy) at the document point (x, y) scrolls: the innermost one under the point that can move in the direction of the gesture. blocked is true when the gesture ends at a container that cannot move any further and has overscroll-behavior contain or none, so it must not scroll anything else; found is false when no container takes it and the viewport should. It uses the last layout and never waits for a new one.

func (*Tab) ScrollTargetOf

func (t *Tab) ScrollTargetOf(id int64) (ScrollTarget, bool)

ScrollTargetOf is the current scroll state of the element with backend id, from the last layout.

func (*Tab) ScrollY

func (t *Tab) ScrollY() int

ScrollY is the last value given to SetScrollY (or moved by the wheel).

func (*Tab) SelClear

func (t *Tab) SelClear()

SelClear removes the selection of the document.

func (*Tab) SelFocusRect

func (t *Tab) SelFocusRect() (r [4]float64, ok bool)

SelRowsOf is the rows (document y, CSS px) of the text of the selection, for scrolling it into view; ok is false when nothing is selected or the selection is not on the page.

func (*Tab) SelGet

func (t *Tab) SelGet() SelInfo

SelGet returns the selection of the document.

func (*Tab) SelSet

func (t *Tab) SelSet(aid int64, ao int, fid int64, fo int)

SelSet sets the selection from boundary points given by backend node ids; an id of 0 clears it.

func (*Tab) SelText

func (t *Tab) SelText() string

SelText is the text of the selection of the document, or of the focused text control when its selection is the one that counts.

func (*Tab) SelectAll

func (t *Tab) SelectAll()

SelectAll selects the contents of the focused text control, or of the editing host that holds the caret, or of the whole page.

func (*Tab) SelectDown

func (t *Tab) SelectDown(x, y float64, clicks int, shift bool) bool

SelectDown starts a selection gesture at the page point (x, y): a click puts the caret there, a double click selects the word, a triple click the paragraph, and with shift the selection is extended from where it was. It reports whether the gesture is the selection's (false: the point is not on selectable text, for example on an element with user-select: none, and the selection was cleared).

func (*Tab) SelectMove

func (t *Tab) SelectMove(x, y float64) bool

SelectMove extends the selection gesture in progress to the page point (x, y).

func (*Tab) SelectOption

func (t *Tab) SelectOption(sel, value string) error

SelectOption picks option(s) by value or visible label; supports multi.

func (*Tab) SelectUp

func (t *Tab) SelectUp()

SelectUp ends the selection gesture.

func (*Tab) SelectedOptions

func (t *Tab) SelectedOptions(sel string) ([]string, error)

SelectedOptions lists currently-selected values of a select.

func (*Tab) SetActivationWindow

func (t *Tab) SetActivationWindow(d time.Duration)

SetActivationWindow sets how long a user gesture keeps allowing popups (default 5 s).

func (*Tab) SetAgentLoading

func (t *Tab) SetAgentLoading(on bool)

SetAgentLoading puts this tab in agent loading mode (AgentPolicy): strict minus script limits. The agent bridge calls it per tab for agent-driven loads.

func (*Tab) SetAsyncImages

func (t *Tab) SetAsyncImages(on bool)

SetAsyncImages makes layout start image downloads in the background and go on without them (the box keeps its declared size, or none) instead of waiting for each image in turn; the tab calls the update hook, at most every imageRelayoutEvery, when images have arrived so the window lays out and paints again. Windows turn it on; the headless commands leave it off and get every image in the first layout. It has no effect while a Data Saver policy is in force (its gates are synchronous).

func (*Tab) SetAttributeByBackend

func (t *Tab) SetAttributeByBackend(backendID int64, k, v string) error

func (*Tab) SetAudioMuted

func (t *Tab) SetAudioMuted(m bool)

SetAudioMuted mutes or unmutes everything the tab plays. The media clocks keep running, so a muted video stays in sync.

func (*Tab) SetBackground

func (t *Tab) SetBackground(bg bool)

SetBackground tells the engine the tab is not visible. With a policy that suspends background tabs, page timers stop and page code (fetch, XHR, polling, media) makes no requests until the tab is shown again.

func (*Tab) SetBindingReply

func (t *Tab) SetBindingReply(name, replyJSON string)

SetBindingReply sets the JSON value page code receives from name(...).

func (*Tab) SetBitmapSource

func (t *Tab) SetBitmapSource(nodeID int64, src BitmapSource)

SetBitmapSource registers or replaces the source for a node of the tab's current document; a nil src removes it.

func (*Tab) SetColorScheme

func (t *Tab) SetColorScheme(s string)

func (*Tab) SetDataPolicy

func (t *Tab) SetDataPolicy(p *DataPolicy)

SetDataPolicy sets a per-tab override of the context policy (nil = inherit). "Load fully, once" uses LoadFully; this is for the app's per-site rules.

func (*Tab) SetDocument

func (t *Tab) SetDocument(htmlSrc, finalURL string)

SetDocument parses html, rebuilds the DOM, runs init scripts + page scripts, fires load.

func (*Tab) SetDocumentCookie

func (t *Tab) SetDocumentCookie(raw string)

SetDocumentCookie is the document.cookie setter.

func (*Tab) SetElementScroll

func (t *Tab) SetElementScroll(id int64, x, y float64) (cx, cy float64, changed bool)

SetElementScroll scrolls the element with backend id to (x, y), clamped to its range, and returns the offsets that were applied and whether they differ from before. The next layout places the content there. It may wait for a layout in progress, so it belongs on the tab's worker.

func (*Tab) SetExtraHeaders

func (t *Tab) SetExtraHeaders(h map[string]string)

func (*Tab) SetFocusNode

func (t *Tab) SetFocusNode(id int64)

SetFocusNode records which element has keyboard focus (script's focus handling reports it); it decides where the caret is drawn.

func (*Tab) SetFramesPaused

func (t *Tab) SetFramesPaused(p bool)

SetFramesPaused pauses (true) or resumes the frames' event loops: a background tab should not run its embedded players. A paused frame keeps its pixels.

func (*Tab) SetFullInputSettle

func (t *Tab) SetFullInputSettle(on bool)

SetFullInputSettle makes input actions settle like any other action until it is cleared (Batch.run sets it for the last step).

func (*Tab) SetGeolocation

func (t *Tab) SetGeolocation(lat, lng float64)

func (*Tab) SetMediaBroker

func (t *Tab) SetMediaBroker(b MediaBroker)

SetMediaBroker attaches the application's permission and display-source handler.

func (*Tab) SetOffline

func (t *Tab) SetOffline(on bool)

func (*Tab) SetProgressiveNav

func (t *Tab) SetProgressiveNav(on bool)

SetProgressiveNav makes navigations that page code starts (a clicked link, location.href) progressive too, for windows that drive LoadStep. Navigate stays blocking for explicit callers.

func (*Tab) SetScrollHook

func (t *Tab) SetScrollHook(f func(ScrollRequest))

SetScrollHook registers who moves the viewport when page script asks. With a hook set, script's request does not change the scroll position by itself: the window scrolls (animating when it is smooth), reports the new offset with NoteScrollY and fires the scroll events. Without one (headless) the position changes at once.

func (*Tab) SetScrollY

func (t *Tab) SetScrollY(y int)

SetScrollY tells the engine where the page is scrolled to (CSS px from the top of the document). With a lazy-images policy it fetches the images that came into range and lays the page out again; the document's MutationGen then changes, so a compositor that watches Generation repaints. Cheap when nothing is due.

func (*Tab) SetSelectionHook

func (t *Tab) SetSelectionHook(f func())

SetSelectionHook registers a function called (on whatever goroutine changed it) when the selection or a control's selection changed.

func (*Tab) SetStorageValue

func (t *Tab) SetStorageValue(key, val string)

SetStorageValue writes into the context store for the current origin.

func (*Tab) SetUpdateHook

func (t *Tab) SetUpdateHook(f func())

SetUpdateHook registers f, called (from any goroutine, never with an engine lock held) when the tab has new content a window should paint: images that arrived after the layout that asked for them. nil removes it.

func (*Tab) SetUserAgent

func (t *Tab) SetUserAgent(ua string)

func (*Tab) SetValueRaw

func (t *Tab) SetValueRaw(sel, value string) error

SetValueRaw writes an input's value without events (debugging aid).

func (*Tab) SetViewport

func (t *Tab) SetViewport(w, h int, dsf float64, mobile, landscape bool)

Emulation setters/getters (Playwright parity).

func (*Tab) SetWakeHook

func (t *Tab) SetWakeHook(f func())

SetWakeHook registers f, called (from any goroutine) when asynchronous results are waiting for the page's JavaScript (a detached image finished). A window answers by giving the tab's event loop a slice.

func (*Tab) SetWindowName

func (t *Tab) SetWindowName(n string)

SetWindowName sets window.name (used by embedders that open tabs for a target).

func (*Tab) Settle

func (t *Tab) Settle(d time.Duration)

Settle pumps the page's event loop for up to d (exported for RPC waits).

func (*Tab) Skipped

func (t *Tab) Skipped() []SkippedItem

Skipped lists what the policy withheld on the current page.

func (*Tab) Snapshot

func (t *Tab) Snapshot() ([]*NodeInfo, error)

Snapshot returns an accessibility-style tree (roles/names/states) which is what AI agents should read instead of raw HTML — far fewer tokens.

func (*Tab) StateLog

func (t *Tab) StateLog(sinceSID int64) []Event

func (*Tab) StopLoading

func (t *Tab) StopLoading()

StopLoading abandons the pending part of a progressive load (the stop button): what has run stays, the rest of the scripts never run.

func (*Tab) StorageSnapshot

func (t *Tab) StorageSnapshot() map[string]string

StorageSnapshot returns localStorage+sessionStorage merged view for agents.

func (*Tab) SubmitFormBackend

func (t *Tab) SubmitFormBackend(id int64) error

SubmitFormBackend submits the form with (or enclosing) the given node id.

func (*Tab) SubmitFormFor

func (t *Tab) SubmitFormFor(sel string) error

SubmitFormFor submits the form enclosing sel (GET navigates with the query, POST sends application/x-www-form-urlencoded) and installs the response.

func (*Tab) TakeQuietRows

func (t *Tab) TakeQuietRows() (top, bottom float64, ok bool)

TakeQuietRows returns the document rows the quiet changes since the last call can have touched.

func (*Tab) Tap

func (t *Tab) Tap(sel string) error

Tap dispatches touchstart/touchend and follows link semantics.

func (*Tab) Text

func (t *Tab) Text(sel string) (string, error)

Text returns innerText-like extraction for agents (structured, whitespace-normalised).

func (*Tab) TextByBackend

func (t *Tab) TextByBackend(backendID int64) string

func (*Tab) Title

func (t *Tab) Title() string

Title reads the live <title> so changes made by page scripts are visible.

func (*Tab) Top

func (t *Tab) Top() *Tab

Top is the top-level tab of a frame tree (the tab itself when it is top-level).

func (*Tab) TraceNetwork

func (t *Tab) TraceNetwork(on bool)

TraceNetwork switches the per-request connection phases (DNS, connect, TLS, time to first byte) on or off for this tab.

func (*Tab) Type

func (t *Tab) Type(sel, text string, delay time.Duration) error

Type simulates per-character keystrokes into an input target.

func (*Tab) URL

func (t *Tab) URL() string

func (*Tab) Uncheck

func (t *Tab) Uncheck(sel string) error

func (*Tab) Unroute

func (t *Tab) Unroute(glob string)

Unroute removes one previously installed rule by its glob pattern.

func (*Tab) UnrouteAll

func (t *Tab) UnrouteAll()

func (*Tab) UserActive

func (t *Tab) UserActive() bool

UserActive reports whether the tab's page had a user gesture within the last five seconds.

func (*Tab) UserAgent

func (t *Tab) UserAgent() string

func (*Tab) Viewport

func (t *Tab) Viewport() (w, h int, dsf float64, mobile, landscape bool)

func (*Tab) WaitForFunction

func (t *Tab) WaitForFunction(expr string, timeout time.Duration) error

WaitForFunction polls a JS expression until truthy or timeout.

func (*Tab) WaitForLoadState

func (t *Tab) WaitForLoadState(state string, timeout time.Duration) error

WaitForLoadState waits for domcontentloaded/load (both synchronous here — Navigate completes after scripts run — so this validates readiness).

func (*Tab) WaitForSelector

func (t *Tab) WaitForSelector(sel, state string, timeoutMs float64) (int, error)

WaitForSelector polls until sel satisfies state (attached|detached|visible| hidden|enabled) or timeout ms elapses. Returns match count when satisfied.

func (*Tab) WaitForURL

func (t *Tab) WaitForURL(pattern string, timeout time.Duration) error

WaitForURL blocks until the tab URL matches pattern (glob).

func (*Tab) WaitFrames

func (t *Tab) WaitFrames(d time.Duration) bool

WaitFrames waits until the frames of this document (and theirs) have finished loading or the timeout passes.

func (*Tab) WheelAt

func (t *Tab) WheelAt(x, y, dx, dy int) bool

WheelAt routes a wheel gesture at the document point (x, y) to the innermost frame under it that can still scroll; false means no frame took it and the page scrolls.

func (*Tab) WindowClosed

func (t *Tab) WindowClosed() bool

WindowClosed reports whether the window is gone as far as other windows can tell.

func (*Tab) WindowName

func (t *Tab) WindowName() string

WindowName is window.name.

type TraceMark

type TraceMark struct {
	Name   string        `json:"name"`
	At     time.Duration `json:"at"`  // offset of the start from the beginning of the navigation
	Dur    time.Duration `json:"dur"` // 0 for an instant
	Detail string        `json:"detail,omitempty"`
}

TraceMark is one phase of a navigation.

type WebRTCHostCandidates

type WebRTCHostCandidates int32

WebRTCHostCandidates says how a page may learn the machine's own addresses through ICE host candidates.

const (
	// WebRTCHostMDNS (default) gathers host candidates but publishes them under
	// a random <uuid>.local name resolved by multicast DNS, as Chrome and Firefox
	// do. When the platform cannot run mDNS the host candidates are dropped, never
	// published as raw addresses.
	WebRTCHostMDNS WebRTCHostCandidates = iota
	// WebRTCHostNone publishes no host candidate at all: connections need a
	// server reflexive or relayed candidate (iceServers configured by the page).
	WebRTCHostNone
	// WebRTCHostRaw publishes raw local addresses. This leaks the local IP to the
	// page and to every peer it talks to; it exists for diagnostics and tests.
	WebRTCHostRaw
)

func WebRTCHostCandidatePolicy

func WebRTCHostCandidatePolicy() WebRTCHostCandidates

WebRTCHostCandidatePolicy returns the current policy.

Source Files

Jump to

Keyboard shortcuts

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