Go SDK Reference
github.com/browserscale/browserscale-go. Every method takes ctx context.Context as its first argument and returns an explicit error; both are omitted from the signatures below for brevity.CloudBrowser
45 methodsCloudBrowser is the SDK-side handle for an active browserscale browser session.
One CloudBrowser corresponds to exactly one browser context. Its own methods act on the context as a whole (proxy, cookies, storage, network, usage); everything that acts on a document is on Page, which CloudBrowser.FocusedPage returns.
AcceptLanguage
method on CloudBrowserAcceptLanguage() → stringAcceptLanguage returns the Accept-Language header value the session was provisioned with.
stringAddReaction
method on CloudBrowserAddReaction(match *Locator) → stringAddReaction registers a one-shot reaction for every page of the browser: it is armed on the pages open now and on every page that opens later — tabs, popups, pages you create — and fires once on each. Use it for the interruptions a site shows wherever you are on it, such as a consent banner. Otherwise it behaves exactly like Page.AddReaction.
The reaction stays registered until you remove it or the session ends; CloudBrowser.ListReactions lists it, and Page.ListReactions lists it on each page where it has not fired yet. Every click is reported as a ContextEventReactionFired, carrying the page it fired on.
| match | *Locator | the CSS/JS locator to watch for |
// Accept the consent banner on whichever page it shows up.
id, err := browser.AddReaction(ctx, browserscale.CSS("button#accept"))
if err != nil {
log.Fatal(err)
}
_ = idstringthe reactionId (pass to CloudBrowser.RemoveReaction)AddReactionWith(match *Locator, opts ReactionOpts) → stringAddReactionWith is the customizable variant of CloudBrowser.AddReaction.
The reaction stays registered until you remove it or the session ends; CloudBrowser.ListReactions lists it, and Page.ListReactions lists it on each page where it has not fired yet. Every click is reported as a ContextEventReactionFired, carrying the page it fired on.
| match | *Locator | the CSS/JS locator to watch for |
| opts | ReactionOpts | reaction customization; see ReactionOpts |
// Close the newsletter modal on every page that opens it.
id, err := browser.AddReactionWith(ctx,
browserscale.CSS("#newsletter-modal"),
browserscale.ReactionOpts{On: browserscale.CSS(".modal-close")},
)stringthe reactionId (pass to CloudBrowser.RemoveReaction)ApiKey
method on CloudBrowserApiKey() → stringApiKey returns the API key used to rent this session.
stringCaptureNetwork
method on CloudBrowserCaptureNetwork(opts NetworkCaptureOptions, onExchange NetworkExchangeHandler) → *NetworkCaptureCaptureNetwork starts capturing the session's network traffic and returns a live view of it.
Every request matching opts.Patterns is reported once it completes, and "every request" is literal: capture sits in the browser process rather than in a page, so cross-process iframes, workers and service workers are included, the headers are the ones actually put on the wire (Cookie and Sec-* included), and each hop of a redirect chain arrives as its own exchange. Requests are never paused, so the page loads at full speed.
This call returns as soon as the capture is running; onExchange then fires in the background while you drive the browser. The capture is armed only after the subscription exists, so nothing that happens after this call returns is missed. Call NetworkCapture.Stop when done — it disarms the capture server-side, which a cancelled context alone does not.
| opts | NetworkCaptureOptions | which requests to capture and whether to keep bodies |
| onExchange | NetworkExchangeHandler | called per exchange; see NetworkExchangeHandler for the |
capture, err := browser.CaptureNetwork(ctx, browserscale.NetworkCaptureOptions{
Patterns: []string{"*/api/*"},
Bodies: browserscale.NetworkBodiesText,
}, func(ex browserscale.NetworkExchange) {
fmt.Println(ex.StatusCode, ex.Method, ex.Url)
})
if err != nil {
log.Fatal(err)
}
defer capture.Stop(ctx)
_, _ = page.Navigate(ctx, "https://example.com", 0)*NetworkCapture*NetworkCapture handle for stopping the capture and inspecting howClearCookies
method on CloudBrowserClearCookies()ClearCookies deletes every cookie in the browser context.
Reports only transport failures - a dead session, a page that is gone, a broken connection. This call has no semantic failure of its own, so there are no error codes to branch on.
_ = browser.ClearCookies(ctx)ClearStorage
method on CloudBrowserClearStorage(origin string)ClearStorage deletes localStorage in the browser context.
| origin | string | if non-empty, only this origin's storage is deleted (e.g. "https://example.com"); empty string deletes all origins |
// Wipe one origin.
_ = browser.ClearStorage(ctx, "https://example.com")
// Wipe everything.
_ = browser.ClearStorage(ctx, "")Close
method on CloudBrowserClose()Close is the defer-friendly form of CloudBrowser.StopBrowser: it uses a background context and drops the final usage. Call StopBrowser instead when you want the usage.
Reports a plain error when the stop API or the connection close fails. The session is released either way; retrying a stop is safe.
browser, err := browserscale.RentBrowser(ctx, cfg)
if err != nil { log.Fatal(err) }
defer browser.Close()CloseConn
method on CloudBrowserCloseConn()CloseConn closes only the gRPC connection, leaving the server-side session running.
Use this to detach without releasing the rental — the common case when you attached with ConnectSession to act on a session owned elsewhere, or when a short-lived handle should not outlive its work but the session must. Contrast with CloudBrowser.Close / CloudBrowser.StopBrowser, which also release the rental via the stop endpoint.
Reports a plain error when the connection cannot be closed cleanly. The local handle is unusable afterwards regardless.
browser, err := browserscale.ConnectSession(ctx, grpcUrl, apiKey, sessionId)
if err != nil { log.Fatal(err) }
defer browser.CloseConn() // detach; the session keeps runningContextEvents
method on CloudBrowserContextEvents(onEvent ContextEventHandler) → *ContextEventsContextEvents registers a listener for the browser's pages: first a snapshot of every page, then each page opening, closing, taking the focus or changing its address or title. Use it to keep a tab list current without polling CloudBrowser.Pages. It also reports every captcha solve (ContextEventCaptchaDetected, ContextEventCaptchaResolved) and every reaction's click (ContextEventReactionFired).
This call returns as soon as the listener is registered; onEvent then fires in the background. Call ContextEvents.Stop when done.
| onEvent | ContextEventHandler | called per event; see ContextEventHandler for the |
tabs := map[string]*browserscale.PageInfo{}
listener, err := browser.ContextEvents(ctx, func(ev browserscale.ContextEvent) {
switch ev.Kind {
case browserscale.ContextEventSnapshot:
clear(tabs)
for _, p := range ev.Pages {
tabs[p.Page.Id()] = p
}
case browserscale.ContextEventPageOpened:
tabs[ev.Page.Id()] = ev.Opened
case browserscale.ContextEventPageClosed:
delete(tabs, ev.Page.Id())
case browserscale.ContextEventPageUpdated:
if t := tabs[ev.Page.Id()]; t != nil {
t.Url, t.Title = ev.Url, ev.Title
}
}
})
if err != nil {
log.Fatal(err)
}
defer listener.Stop()*ContextEvents*ContextEvents handle for stopping the listener and inspecting howCountryCode
method on CloudBrowserCountryCode() → stringCountryCode returns the ISO-3166 country code the server allocated for this session (drives geo-IP and locale defaults).
stringCreatePage
method on CloudBrowserCreatePage() → *PageCreatePage opens a page the way opening a new tab does: an about:blank tab that takes the focus. A browser starts without a page, so this is the first call after renting one. Returns once the page is ready for Page.Navigate.
page, err := browser.CreatePage(ctx)
if err != nil {
log.Fatal(err)
}
_, err = page.Navigate(ctx, "https://example.com", 0)*PageDisableCaptchaAutoSolve
method on CloudBrowserDisableCaptchaAutoSolve() → boolDisableCaptchaAutoSolve stops CloudBrowser.EnableCaptchaAutoSolve. A solve already running finishes; one waiting for the focus is resolved with code "disabled".
if _, err := browser.DisableCaptchaAutoSolve(ctx); err != nil {
log.Fatal(err)
}boolwhether auto-solve was enabledEnableCaptchaAutoSolve
method on CloudBrowserEnableCaptchaAutoSolve(opts CaptchaAutoSolveOpts)EnableCaptchaAutoSolve makes the browser solve captchas as they appear, on every page, frame and popup of the session, including ones opened later. Nothing has to call Page.SolveCaptcha or wait for a Captcha condition.
An action running on the page when a captcha appears (Page.Click, Page.Fill, Page.Type, Page.DragBy, Page.DragTo) is held at its next safe point — between two keys, before the button goes down — and carries on after the solve: a fill types the rest of its text, a click goes for its target again. Its result lists the solve under Captchas. An action started while a solve runs waits for it. Time spent held does not count against the action's timeout, nor against a Page.Wait. Page.InsertText, Page.PressKey and Page.ReleaseKey are refused with code "busy" while a solve runs.
While a Page.Wait with a Captcha condition runs on a page, auto-solve leaves that page's captchas alone, so the wait sees them first.
Each solve is reported on CloudBrowser.ContextEvents: a ContextEventCaptchaDetected and then exactly one ContextEventCaptchaResolved with the same SolveId.
Calling it again replaces the settings; solves already running keep the ones they started with. Auto-solve lasts until CloudBrowser.DisableCaptchaAutoSolve or the end of the session.
| opts | CaptchaAutoSolveOpts | settings; see CaptchaAutoSolveOpts. The zero value uses the |
err := browser.EnableCaptchaAutoSolve(ctx, browserscale.CaptchaAutoSolveOpts{
Unfocused: "focus",
})
if err != nil {
log.Fatal(err)
}
// A captcha that shows up during the fill is solved, then the fill
// carries on.
res, err := page.Fill(ctx, browserscale.CSS("#email"), "user@example.com")
if err == nil && len(res.Captchas) > 0 {
log.Printf("held by %d captcha solve(s)", len(res.Captchas))
}Fingerprint
method on CloudBrowserFingerprint() → stringFingerprint returns the browser fingerprint id in use for this session.
stringFocusedPage
method on CloudBrowserFocusedPage() → *PageFocusedPage returns the page that has the focus: the one a person would be looking at. Once the browser has a page, exactly one has it. A tab or popup a page opens takes it, and closing the focused page hands it on, the way it does for a person.
Input (Page.Click, Page.MoveTo and what builds on them) only acts on the focused page; Page.Focus moves the focus.
page, err := browser.FocusedPage(ctx)
if err != nil {
log.Fatal(err)
}
_, err = page.Navigate(ctx, "https://example.com", 0)*Page| ErrNoPage | the browser has no page yet; CloudBrowser.CreatePage opens the first |
GetAuthSession
method on CloudBrowserGetAuthSession() → *AuthSessionGetAuthSession exports the signed-in primary account and DBSC sessions of this browser context. Reads state in the browser process — no page needed.
Returns nil, nil when the context has neither a signed-in account nor DBSC sessions.
auth, err := browser.GetAuthSession(ctx)
if err != nil {
log.Fatal(err)
}
if auth == nil {
log.Println("no auth/DBSC state")
return
}
// persist auth, then later SetAuthSession on a fresh rent*AuthSession*AuthSession, or nil when there is nothing to exportGetClientIdentity
method on CloudBrowserGetClientIdentity(opts ...IdentityOption) → *ClientIdentityGetClientIdentity returns the session's client identity in one call, and — with WithCookies / WithStorage — its cookies and localStorage folded into the same response. Reads the context configuration directly in the browser process, so no page needs to be open.
| opts | ...IdentityOption | optional WithCookies / WithStorage / WithStorageOrigin |
id, err := browser.GetClientIdentity(ctx, browserscale.WithCookies())
if err != nil {
log.Fatal(err)
}
fmt.Println(id.UserAgent, id.Proxy.Host, len(id.Cookies))*ClientIdentity*ClientIdentity describing the session on the wireGetCookies
method on CloudBrowserGetCookies() → []CookieParamGetCookies returns all cookies currently stored in this session's browser context.
cookies, err := browser.GetCookies(ctx)
if err != nil {
log.Fatal(err)
}
for _, c := range cookies {
fmt.Println(c.Name, "=", c.Value)
}[]CookieParam[]CookieParam, one per cookie in the contextGetPage
method on CloudBrowserGetPage(pageId string) → *PageGetPage returns the Page with this id. It makes no call and does not check the id: a page that is gone shows on the Page's first call.
| pageId | string | a page id, as reported by CloudBrowser.Pages or an error |
page := browser.GetPage(savedPageId)
_, err := page.Navigate(ctx, "https://example.com", 0)*PageGetStorage
method on CloudBrowserGetStorage(origin string) → []StorageOriginEntryGetStorage returns the localStorage contents of this session's browser context, grouped by origin.
The storage database is read directly in the browser process, so no page needs to be open. Only first-party localStorage is included — sessionStorage is per-tab and not covered.
| origin | string | if non-empty, only this origin is returned (e.g. "https://example.com"); empty string returns all origins |
storage, err := browser.GetStorage(ctx, "")
if err != nil {
log.Fatal(err)
}
for _, e := range storage {
for _, item := range e.Items {
fmt.Println(e.Origin, item.Key, "=", item.Value)
}
}[]StorageOriginEntry[]StorageOriginEntry, one per origin with localStorage dataGetStreamConfig
method on CloudBrowserGetStreamConfig() → []IceServerGetStreamConfig returns the ICE servers (TURN URL + short-lived credentials) to put in your RTCPeerConnection BEFORE creating the offer, so it can gather relay candidates.
Live streaming is a two-step, client-offerer handshake: call GetStreamConfig, build your peer with the returned servers, create an offer, then pass its SDP to CloudBrowser.StartStream and apply the returned answer.
ice, err := browser.GetStreamConfig(ctx)
if err != nil { log.Fatal(err) }
// configure your RTCPeerConnection with ice, then create an offer …[]IceServerthe ICE servers for the client RTCPeerConnectionGetUsage
method on CloudBrowserGetUsage() → *SessionUsageGetUsage reports what this session's browser has consumed so far.
Everything but MinMemory and AverageMemory only ever grows, so polling and diffing two readings gives the cost of what ran in between. The final figures need no call of their own: CloudBrowser.StopBrowser returns them.
before, _ := browser.GetUsage(ctx)
_, _ = page.Navigate(ctx, "https://example.com", 0)
after, _ := browser.GetUsage(ctx)
fmt.Printf("navigation cost %.2fs of CPU\n", after.CpuTime-before.CpuTime)*SessionUsage*SessionUsage as of nowGrpcUrl
method on CloudBrowserGrpcUrl() → stringGrpcUrl returns the gRPC endpoint the session is connected to.
stringListReactions
method on CloudBrowserListReactions() → []ReactionInfoListReactions returns the reactions registered with CloudBrowser.AddReaction that have not been removed. Each stays listed while it fires on page after page; Page.ListReactions shows where it is still pending.
all, err := browser.ListReactions(ctx)
for _, r := range all {
log.Printf("browser-wide reaction %s", r.ReactionID)
}[]ReactionInfothe reactions registered for every pageModifyRequest
method on CloudBrowserModifyRequest(urlPattern string, body string, timeoutMs float64, mods []HeaderModification) → *InterceptedRequestModifyRequest waits for the next request whose URL matches urlPattern, applies the supplied header modifications (and optional body replacement), then forwards the modified request.
One-shot: consumes the first matching request. Pass nil/empty mods to leave headers untouched and only override the body.
| urlPattern | string | URL wildcard to wait for |
| body | string | replacement request body; empty leaves the original body |
| timeoutMs | float64 | per-call timeout in milliseconds; 0 uses the server default |
| mods | []HeaderModification | HeaderModification entries; see HeaderModification for the fields |
req, err := browser.ModifyRequest(ctx, "*/api/me", "", 5000, []browserscale.HeaderModification{
{Action: browserscale.HeaderModificationAdd, Name: "X-Trace", Value: "abc123"},
{Action: browserscale.HeaderModificationRemove, Name: "Cookie"},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("forwarded headers:", req.Headers)*InterceptedRequest*InterceptedRequest carrying the method/URL/headers/body thatPages
method on CloudBrowserPages() → []*PageInfoPages returns all open pages (tabs and popups) for this session's browser context.
Each PageInfo carries the Page to act on, its URL, title, viewport, a full nested frame tree (out-of-process iframes are children of the page's main frame), whether it has the focus, and where it came from.
pages, err := browser.Pages(ctx)
if err != nil {
log.Fatal(err)
}
for _, p := range pages {
if p.IsPopup && p.Opener != nil {
fmt.Println("popup", p.Url, "opened by", p.Opener.Id())
}
}[]*PageInfo[]*PageInfo for every page currently open in the contextReadNetworkBody
method on CloudBrowserReadNetworkBody(bodyId string) → []byte, boolReadNetworkBody reads a whole captured body: an exchange's RequestBodyId or ResponseBodyId.
Bodies are stored by the browser, not sent with the exchange, so reading one is a separate call. They stay readable after the capture stops, until the session ends.
The body is fetched in ranges and assembled in memory. For very large bodies, use CloudBrowser.ReadNetworkBodyRange to process them piece by piece.
| bodyId | string | RequestBodyId or ResponseBodyId from a NetworkExchange |
capture, _ := browser.CaptureNetwork(ctx, browserscale.NetworkCaptureOptions{
Patterns: []string{"*/api/*"},
Bodies: browserscale.NetworkBodiesText,
}, func(ex browserscale.NetworkExchange) {
if ex.ResponseBodyId == "" {
return
}
go func() {
body, _, err := browser.ReadNetworkBody(ctx, ex.ResponseBodyId)
if err == nil {
fmt.Println(ex.Url, len(body))
}
}()
})
defer capture.Stop(ctx)[]byte, bool[]byte holding the body, bool reporting whether the kept body isReadNetworkBodyRange(bodyId string, offset int64, length int64) → *NetworkBodyRangeReadNetworkBodyRange reads up to length bytes of a captured body starting at offset.
A single call returns at most 2 MiB; length 0 reads that much. Loop on offset + len(Data) until it reaches TotalSize to stream a large body.
| bodyId | string | RequestBodyId or ResponseBodyId from a NetworkExchange |
| offset | int64 | first byte to read |
| length | int64 | bytes to read; 0 reads the per-call maximum |
*NetworkBodyRange*NetworkBodyRange with the bytes and the body's total size, and anRemoveReaction
method on CloudBrowserRemoveReaction(reactionID string) → boolRemoveReaction removes a reaction by id, wherever it is pending: a reaction from CloudBrowser.AddReaction stops for every page, including the ones that open later. It returns false if no reaction with this id was pending anywhere.
| reactionID | string | id returned by CloudBrowser.AddReaction or Page.AddReaction |
removed, err := browser.RemoveReaction(ctx, id)booltrue if a pending reaction with this id existed and was removedSessionId
method on CloudBrowserSessionId() → stringSessionId returns the unique server-assigned id for this browser session.
stringSetAuthSession
method on CloudBrowserSetAuthSession(session AuthSession)SetAuthSession imports an auth session so the context comes up signed in (and syncing if SyncConsent) with its DBSC sessions restored.
Call before navigating. Pair with SetCookies / SetStorage to fully restore a persona.
| session | AuthSession | session as returned by GetAuthSession |
_ = browser.SetAuthSession(ctx, *saved)
_ = page.Navigate(ctx, "https://mail.google.com")SetBlockList
method on CloudBrowserSetBlockList(patterns []string)SetBlockList replaces the session's URL blocklist.
Any request whose URL matches one of the supplied patterns is blocked before it leaves the browser. Patterns are simple URL wildcards (* matches any character span). Pass a nil/empty slice to clear the blocklist and let everything through.
| patterns | []string | URL wildcards to block; nil or empty clears the list |
_ = browser.SetBlockList(ctx, []string{
"*.doubleclick.net/*",
"*googletagmanager.com*",
})SetCookies
method on CloudBrowserSetCookies(cookies []CookieParam)SetCookies writes the supplied cookies into the browser context.
Existing cookies with the same (name, domain, path) tuple are overwritten. Pass an empty slice for a no-op.
| cookies | []CookieParam | cookies to write; empty slice is a no-op |
secure := true
httpOnly := true
sameSite := "Lax"
_ = browser.SetCookies(ctx, []browserscale.CookieParam{
{
Name: "auth",
Value: "tok",
Domain: "example.com",
Path: "/",
Secure: &secure,
HTTPOnly: &httpOnly,
SameSite: &sameSite,
},
})SetProxy
method on CloudBrowserSetProxy(proxyHost string, proxyPort int32, proxyUsername string, proxyPassword string, opts ...ProxyOption)SetProxy changes the runtime proxy for this session.
Takes effect for new requests immediately; in-flight requests keep their original routing. Pass an empty proxyHost to clear the proxy and route directly.
| proxyHost | string | upstream proxy host; empty disables the proxy |
| proxyPort | int32 | upstream proxy port; ignored when proxyHost is empty |
| proxyUsername | string | proxy auth user (empty for unauthenticated proxies) |
| proxyPassword | string | proxy auth password (empty for unauthenticated proxies) |
| opts | ...ProxyOption | ProxyWithScheme and ProxyWithMasque, as for a rental |
_ = browser.SetProxy(ctx, "proxy.example.com", 8080, "user", "pass")
_ = browser.SetProxy(ctx, "proxy.example.com", 1080, "user", "pass",
browserscale.ProxyWithScheme(browserscale.ProxySOCKS5))SetStaticPaths
method on CloudBrowserSetStaticPaths(blobName string, patterns []string)SetStaticPaths configures the session to serve cached static responses for requests matching the given patterns from blobName.
Useful for replaying frozen page assets (HTML/JS/CSS/images) without hitting the origin every time. The cache backend itself (blob storage, CDN, …) is configured server-side. Pass an empty patterns slice to disable caching for this session.
| blobName | string | server-side identifier of the snapshot to serve from |
| patterns | []string | URL wildcards to redirect to the cache; nil/empty disables |
_ = browser.SetStaticPaths(ctx, "snap-2026-05", []string{"*.example.com/*"})SetStorage
method on CloudBrowserSetStorage(storage []StorageOriginEntry)SetStorage writes localStorage entries into the browser context, grouped by origin.
Accepts the same structure GetStorage returns, so a dump can be fed back verbatim. Existing keys are overwritten. Works without any open page; pages that are already open will not observe the writes until they reload.
| storage | []StorageOriginEntry | entries to write, grouped by origin |
_ = browser.SetStorage(ctx, []browserscale.StorageOriginEntry{
{
Origin: "https://example.com",
Items: []browserscale.StorageItem{
{Key: "token", Value: "abc123"},
{Key: "theme", Value: "dark"},
},
},
})StartNetworkCapture
method on CloudBrowserStartNetworkCapture(opts NetworkCaptureOptions)StartNetworkCapture arms a capture without subscribing to it.
Use it when the reader lives somewhere else — another process, or a later ConnectSession against the same session. Most callers want CloudBrowser.CaptureNetwork instead, which arms and subscribes together. Calling this again replaces the running capture.
| opts | NetworkCaptureOptions | which requests to capture and whether to keep bodies |
StartStream
method on CloudBrowserStartStream(offerSDP string) → StreamAnswerStartStream answers your WebRTC SDP offer and starts streaming the session as a video track. The browser is the answerer; you are the offerer (see CloudBrowser.GetStreamConfig for the credentials to build the offer).
The stream shows the page that has the focus and follows it: when a tab or popup comes to the front, or Page.Focus brings another page forward, picture and input move there and the new viewport arrives on the "input" channel. While the shown page closes, the last picture stays until the next page is shown; the stream keeps running.
| offerSDP | string | your RTCPeerConnection's SDP offer |
stream, err := browser.StartStream(ctx, offer.SDP)
if err != nil { log.Fatal(err) }
// peer.SetRemoteDescription({type: "answer", sdp: stream.AnswerSDP}) …StreamAnswerthe SDP answer plus the viewport to map input coordinates into| ErrNoPage | the browser has no page to show yet; CloudBrowser.CreatePage opens the first |
StopNetworkCapture
method on CloudBrowserStopNetworkCapture() → boolStopNetworkCapture disarms the session's capture.
boolbool reporting whether a capture was running, and an errorStopStream
method on CloudBrowserStopStream()StopStream tears down the session's live video stream. It is safe to call even if no stream is running.
Reports only transport failures - a dead session, a broken connection. Stopping a stream that is not running is a no-op rather than a failure, so there are no error codes to branch on.
if err := browser.StopStream(ctx); err != nil { log.Fatal(err) }StreamNetworkExchanges
method on CloudBrowserStreamNetworkExchanges(onExchange NetworkExchangeHandler) → *NetworkCaptureStreamNetworkExchanges subscribes to the session's capture without arming one, for reading a capture that CloudBrowser.StartNetworkCapture armed elsewhere. Several readers can watch the same capture, each with its own buffer.
Stopping the returned view detaches this reader and leaves the capture running, since other readers may still be attached.
| onExchange | NetworkExchangeHandler | called per exchange; see NetworkExchangeHandler for the |
*NetworkCapture*NetworkCapture attached to whatever capture is running; onExchangeTimezone
method on CloudBrowserTimezone() → stringTimezone returns the IANA timezone the session was provisioned with (e.g. "Europe/Berlin").
stringWaitForAnyRequest
method on CloudBrowserWaitForAnyRequest(timeoutMs float64, patterns []RequestPattern) → int32, *InterceptedRequestWaitForAnyRequest blocks until the next request whose URL matches one of the supplied patterns is observed.
Returns the matched pattern's index and the captured request. When patternsi.Abort is true the request is dropped with an empty 200 response instead of being sent to the network.
| timeoutMs | float64 | per-call timeout in milliseconds; 0 uses the server default |
| patterns | []RequestPattern | one or more URL patterns (with optional Abort flags) |
idx, req, err := browser.WaitForAnyRequest(ctx, 5000, []browserscale.RequestPattern{
{URL: "*/api/login"},
})
if err != nil {
log.Fatal(err)
}
_ = idx
fmt.Println(req.Method, req.Url)int32, *InterceptedRequestint32 index of the matched pattern, *InterceptedRequest withWaitForAnyResponse(timeoutMs float64, patterns []RequestPattern) → int32, *InterceptedResponseWaitForAnyResponse blocks until the next response whose URL matches one of the supplied patterns is observed.
Same shape as CloudBrowser.WaitForAnyRequest but on the response phase. When patternsi.Abort is true the page receives an empty 200 instead of the real response.
| timeoutMs | float64 | per-call timeout in milliseconds; 0 uses the server default |
| patterns | []RequestPattern | one or more URL patterns (with optional Abort flags) |
idx, resp, err := browser.WaitForAnyResponse(ctx, 5000, []browserscale.RequestPattern{
{URL: "*/api/login"},
})
if err != nil {
log.Fatal(err)
}
_ = idx
fmt.Println(resp.StatusCode)int32, *InterceptedResponseint32 index of the matched pattern, *InterceptedResponse withLocator
6 methodsLocator says what a call is about: an element, and where on the page to look for it. It is used as a wait condition (passed to Page.Wait), as the target of an action (passed to Page.Click, Page.Fill, ...), and as a container that another locator is looked for in (passed to Locator.In).
Build one with a constructor, never by hand:
- CSS, JS: an element by selector or by expression - a result's Ref (or Ref for a reference read from an observation): the very element an earlier call found - At: a point instead of an element, for Page.Click and Page.MoveTo - FrameURL, FrameName, MainFrame, AnyFrame: a frame, to look in
Where a locator looks is decided by Locator.In. Without it a CSS locator means the whole page, every frame included, and a JS locator runs in the page's main document.
Not every part is meaningful everywhere: Visible and Steady apply to wait conditions and reactions, At to Click and MoveTo, and the frame constructors only name a place to look in, never a target.
In
method on LocatorIn(container *Locator) → *LocatorIn says where this locator is looked for: inside the container.
The container is another locator, and what it means depends on what it finds:
- an iframe (CSS, JS or a reference naming the iframe element): its document, same-origin or not - any other element: its subtree. For a component with a shadow tree that includes the shadow tree, open or closed, so a host element is the way into it - FrameURL, FrameName, FrameByID, MainFrame, AnyFrame: that frame
A container can itself be put in a container, to any depth. Calling In again on the result wraps one level further out, so a.In(b).In(c) is a in b in c.
The whole chain is looked up anew each time the call looks for its element. A call that waits (Page.Click, Page.Fill, Page.Wait, a reaction) therefore also waits for the iframe and the container to appear, and a container that never does is reported as "container_not_found" with the link that was missing.
In returns a new Locator and leaves both this one and the container as they were, so a container can be kept and reused.
| container | *Locator | where to look |
pay := browserscale.CSS("iframe[title='Secure payment']")
_, _ = page.Fill(ctx, browserscale.CSS("input[name=cardnumber]").In(pay), card)
_, _ = page.Fill(ctx, browserscale.CSS("input[name=cvc]").In(pay), cvc)// A subtree, and a shadow host.
dialog := browserscale.CSS("[role=dialog]")
_, _ = page.Click(ctx, browserscale.CSS("button.close").In(dialog))
picker := browserscale.CSS("date-picker")
_, _ = page.Click(ctx, browserscale.CSS("button.next").In(picker))// The iframe a wait found, as the place to look next.
frame, _ := page.Wait(ctx, browserscale.CSS("iframe.widget"))
_, _ = page.Click(ctx, browserscale.CSS("button").In(frame.Element.Ref))*Locatora new *Locator for the same element, confined to the containerMarshalJSON
method on LocatorMarshalJSON() → []byteMarshalJSON writes the locator as text, so that a result printed as JSON shows what its Ref is: a reference as Locator.RefString gives it, ready for Ref, and any other locator as Locator.String describes it.
[]byteRefString
method on LocatorRefString() → stringRefString returns the reference this Locator stands for, in the form Ref takes, or "" when it is not a reference. For writing a reference down or handing it to something that is not Go code.
res, _ := page.Wait(ctx, browserscale.CSS(".result"))
saved := res.Element.Ref.RefString()
// ... later, in the same session:
_, _ = page.Click(ctx, browserscale.Ref(saved))stringthe reference as text, or ""Steady
method on LocatorSteady(ms float64) → *LocatorSteady requires the element to keep a stable position and size for at least ms milliseconds before the wait matches.
Settling defaults to 500ms, so pass 0 to match the instant the element is found. Has no effect for JS expressions that return a non-Element value, nor when the Locator is used as an action target.
| ms | float64 | steady-state duration in milliseconds; 0 disables |
_, _ = page.Wait(ctx, browserscale.CSS(".banner").Steady(0))*Locatorthe same Locator for chainingString
method on LocatorString() → stringString describes the locator for logs and error messages: what it names and what it is looked for in, outermost last.
stringVisible
method on LocatorVisible(v bool) → *LocatorVisible enforces or disables the visibility check for this Locator's wait condition.
Visibility is required by default, so pass false to wait for DOM presence alone. Has no effect when the Locator is used as an action target — actions never check visibility before dispatching.
| v | bool | true to require visibility, false to skip the check |
_, _ = page.Wait(ctx, browserscale.CSS("#hidden").Visible(false))*Locatorthe same Locator for chainingBrowserConfig
6 methodsBrowserConfig holds all parameters for renting a browser session. Use NewBrowserConfig with the required fields, then chain optional setters.
UnstableWithGpuEnabled
method on BrowserConfigUnstableWithGpuEnabled(enabled bool) → *BrowserConfigUnstableWithGpuEnabled restricts the rental to hosts that render on a physical GPU instead of the software renderer.
Unstable API — do not build on it. It exists to compare GPU-backed hosts against software rendering while that rollout is in progress; once every host is GPU-backed the flag becomes meaningless and is removed. Note that it narrows the pool: the rental fails rather than falling back to a software-rendered host, so it can report no capacity while ordinary rentals still succeed.
| enabled | bool | true to require a GPU-backed host |
cfg := browserscale.NewBrowserConfig(apiKey, 600, "", 0, "", "").UnstableWithGpuEnabled(true)*BrowserConfigthe modified *BrowserConfig for chainingWithCountryCode
method on BrowserConfigWithCountryCode(countryCode string) → *BrowserConfigWithCountryCode sets the geo-IP country code for the rented session.
Drives both the assigned exit-IP region and the locale defaults (Accept- Language, timezone fallback) when those are not overridden separately.
| countryCode | string | ISO-3166 country code (e.g. "DE", "US") |
cfg := browserscale.NewBrowserConfig(apiKey, 600, "", 0, "", "").WithCountryCode("DE")*BrowserConfigthe modified *BrowserConfig for chainingWithFingerprint
method on BrowserConfigWithFingerprint(fingerprint string) → *BrowserConfigWithFingerprint pins a specific browser fingerprint id for the session.
When omitted the server picks a fingerprint based on the country code. Pass a known id (e.g. one returned by a previous rental) to keep fingerprints stable across sessions.
| fingerprint | string | server-side fingerprint id |
cfg := browserscale.NewBrowserConfig(apiKey, 600, "", 0, "", "").WithFingerprint("fp_abc123")*BrowserConfigthe modified *BrowserConfig for chainingWithMasque
method on BrowserConfigWithMasque(hostPort string) → *BrowserConfigWithMasque routes the session's HTTP/3 traffic through a MASQUE proxy (CONNECT-UDP, RFC 9298), authenticated with the username and password of the proxy passed to NewBrowserConfig.
The MASQUE proxy has to leave from the same exit IP as the proxy, so the browser shows one address: the rental is refused when they differ. Use credentials that keep their IP (a sticky session) where the provider rotates. Without a MASQUE proxy, HTTP/3 falls back to the proxy over TCP.
| hostPort | string | the MASQUE proxy as "host:port" |
cfg := browserscale.NewBrowserConfig(apiKey, 600, "proxy.example.com", 8080, "user", "pass").
WithMasque("masque.example.com:443")*BrowserConfigthe modified *BrowserConfig for chainingWithProxyScheme
method on BrowserConfigWithProxyScheme(scheme ProxyScheme) → *BrowserConfigWithProxyScheme sets the protocol of the proxy passed to NewBrowserConfig. Without it the proxy is an HTTP proxy.
| scheme | ProxyScheme | ProxyHTTP or ProxySOCKS5 |
cfg := browserscale.NewBrowserConfig(apiKey, 600, "proxy.example.com", 1080, "user", "pass").
WithProxyScheme(browserscale.ProxySOCKS5)*BrowserConfigthe modified *BrowserConfig for chainingWithTimezone
method on BrowserConfigWithTimezone(timezone string) → *BrowserConfigWithTimezone sets the IANA timezone for the rented session.
| timezone | string | IANA timezone (e.g. "Europe/Berlin") |
cfg := browserscale.NewBrowserConfig(apiKey, 600, "", 0, "", "").WithTimezone("Europe/Berlin")*BrowserConfigthe modified *BrowserConfig for chainingBrowserInfo
1 methodBrowserInfo describes one running session as ListBrowsers reports it.
| SessionId | string | |
| GrpcUrl | string | GrpcUrl is the endpoint this session is driven from — the same one rent returned. It is what makes a listed id usable: pass it to ConnectSession, or call BrowserInfo.Connect. |
| StartTime | int64 | StartTime is unix seconds. |
| RentDuration | int | RentDuration is the rental length in seconds; 0 means unlimited. |
| RemainingSeconds? | *int | RemainingSeconds counts down to the end of the rental, and is nil for an unlimited one. |
| CountryCode | string | |
| Timezone | string | |
| ProxyHost | string | |
| PublicIp | string | PublicIp is the address the session egresses from. |
| GpuIndex? | *int | GpuIndex is the physical card the session renders on, nil on a software-rendered host. |
Connect
method on BrowserInfoConnect(apiKey string) → *CloudBrowserConnect attaches to this listed session over gRPC.
Shorthand for ConnectSession with the URL and id already in hand. The returned handle owns no rental, so CloudBrowser.CloseConn detaches without ending the session — which is usually what you want for a session you found rather than rented.
| apiKey | string | API key the session was rented with |
browsers, _ := browserscale.ListBrowsers(ctx, apiKey)
browser, err := browsers[0].Connect(ctx, apiKey)
if err != nil { log.Fatal(err) }
defer browser.CloseConn() // detach; the session keeps running*CloudBrowser*CloudBrowser attached to the sessionCaptchaCondition
1 methodCaptchaCondition is the wait condition built by Captcha. It is accepted by Page.Wait only — it is not a Locator, so no element action takes it.
In
method on CaptchaConditionIn(container *Locator) → *CaptchaConditionIn confines the captcha condition to a container, the way Locator.In does for an element: only a challenge inside that frame or element counts. Without it, a challenge anywhere on the page does.
| container | *Locator | where to look |
// Only a challenge in the checkout frame, not the one in the chat widget.
checkout := browserscale.FrameURL("*checkout.example.com/*")
_, _ = page.Wait(ctx, browserscale.Captcha().In(checkout))*CaptchaConditiona new *CaptchaCondition confined to the containerContextEvents
3 methodsContextEvents is a running listener, returned by CloudBrowser.ContextEvents. Events go to the handler passed there; this handle only exists to stop listening and to report how it ended.
Err
method on ContextEventsErr()Err reports why the listener ended. It returns nil while it is still running, and after a clean stop, a cancelled context, or the session ending normally.
Stop
method on ContextEventsStop()Stop ends the listener. Idempotent, and safe to defer.
Once it returns, the handler is no longer running and everything it wrote is visible to the calling goroutine. Do not call it from inside the handler: it waits for the handler to return. Cancel the context passed to CloudBrowser.ContextEvents there instead.
Wait
method on ContextEventsWait()Wait blocks until the listener ends — ContextEvents.Stop, a cancelled context, a dead session or a transport failure — and returns ContextEvents.Err.
DomMirror
14 methodsDomMirror is a live copy of a page's DOM, across every frame in it, returned by Page.MirrorDom.
The browser sends the top of the tree once and from then on only what changed in the part you expanded, so a page that churns inside a collapsed subtree costs one number per batch instead of a re-serialized document.
It is one tree. An <iframe> is an element whose one child is the document it hosts; expanding it fetches that document and starts mirroring the frame, collapsing it stops again, and a frame navigating arrives as its owner's child being replaced.
Node ids restart per frame, so a node's address is the pair (DomNode.FrameId, DomNode.BackendNodeId) and never the id alone.
Every method is safe to call from any goroutine.
Collapse
method on DomMirrorCollapse(node *DomNode)Collapse stops reporting changes inside a node, called when the user closes it. The node itself stays in the tree and keeps reporting its child count. A child frame below it stops being mirrored too.
| node | *DomNode | the node to close |
Err
method on DomMirrorErr()Err reports why the mirror ended. It returns nil while it is still running, and after a clean stop, a cancelled context, or the session ending normally.
Expand
method on DomMirrorExpand(node *DomNode, depth int32)Expand fetches a node's children and starts reporting changes inside them. This is what a tree view calls when the user opens a node.
On an <iframe> the one child is the document it hosts, and this call is what starts mirroring that frame. Nothing about the result says a process boundary was crossed; it is a child list like any other.
A node that left the tree while the call was in flight is not an error and changes nothing.
| node | *DomNode | the node to open, from DomMirror.Root or DomMirror.Node |
| depth | int32 | levels below the node; 0 uses the server default of 1 |
FrameIds
method on DomMirrorFrameIds() → []stringFrameIds returns every frame with a document in the tree, main frame first. A frame whose <iframe> has not been expanded is not mirrored and not listed.
[]stringIsExpanded
method on DomMirrorIsExpanded(node *DomNode) → boolIsExpanded reports whether this node's children are known. Changes inside a node that is not expanded arrive only as an updated ChildNodeCount.
| node | *DomNode |
boolLocator
method on DomMirrorLocator(node *DomNode) → *LocatorLocator turns a mirror node into a reference that Page.Click, Page.Fill and every other call with a target takes: the way to act on a node picked in the tree. See Page.NodeRef, which this calls with the node's address.
| node | *DomNode | a node of this mirror |
button, err := mirror.Locator(ctx, node)
if err != nil {
log.Fatal(err)
}
_, _ = page.Click(ctx, button)*Locator*Locator naming the node, usable as a target or a containerMainFrameId
method on DomMirrorMainFrameId() → stringMainFrameId returns the page's main frame.
stringNode
method on DomMirrorNode(frameId string, backendNodeId int32) → *DomNodeNode looks up a node by its address, or nil if the mirror does not hold it.
| frameId | string | |
| backendNodeId | int32 |
Resync
method on DomMirrorResync()Resync throws away the local copy of the whole page and fetches a fresh one. It happens automatically whenever the browser says the copy is void, so you rarely need to call it.
Reveal
method on DomMirrorReveal(backendNodeId int32, frameId string) → []*DomNodeReveal brings a node into the tree together with its ancestors and their siblings, and starts reporting changes along that path.
Use it to focus a node you do not hold — an Page.InspectAtPosition hit, say. You cannot walk up to it yourself: it is not in your tree, so there is nothing to walk from.
The node may be in a frame nobody opened, and that works: the chain comes back crossing the frame boundaries it has to, and those frames start being mirrored, exactly as if you had expanded your way there by hand.
| backendNodeId | int32 | the node to reach |
| frameId | string | the frame its id belongs to; empty targets the main frame |
[]*DomNode[]*DomNode the ancestor chain, the main document first, or nil if theRoot
method on DomMirrorRoot() → *DomNodeRoot returns the main frame's document, or nil before the first snapshot arrived.
The result is an immutable snapshot: the mirror will not modify the nodes it hands out, so it stays consistent to walk while the page keeps changing.
Seq
method on DomMirrorSeq() → uint64Seq returns the page sequence of the last change applied. One clock for the whole page: a change in an out-of-process iframe and one in the main document are ordered against each other.
uint64Stop
method on DomMirrorStop()Stop stops mirroring and detaches the reader. Idempotent, and safe to defer.
Once it returns, the change handler is no longer running and everything it wrote is visible to the calling goroutine.
To stop from inside the handler, call Page.StopDomMirror instead: Stop waits for the handler to return, so calling it from there would wait on itself until ctx expires.
ctx covers the call that stops the mirror server-side, so pass a live one: the context the mirror was created with may already be cancelled by the time you stop.
Reports only transport failures - a dead session, a page that is gone, a broken connection. The local reader is shut down regardless, and stopping a mirror that is not running is a no-op, so there are no error codes to branch on.
Wait
method on DomMirrorWait()Wait blocks until the mirror ends — DomMirror.Stop, a cancelled context, a dead session or a transport failure — and returns DomMirror.Err.
FrameInfo
2 methodsFrameInfo describes a single frame within a page's frame tree, as Page.Frames and CloudBrowser.Pages report it.
Locator
method on FrameInfoLocator() → *LocatorLocator returns this frame as a container for Locator.In, Page.EvaluateIn and ObservationOpts.Scope. It names the frame by its id, which holds for this session; see FrameByID.
frames, _ := page.Frames(ctx)
for _, f := range frames.Children {
if f.IsVisible && strings.Contains(f.Url, "checkout") {
_, _ = page.Click(ctx, browserscale.CSS("button.pay").In(f.Locator()))
}
}Walk
method on FrameInfoWalk(fn func(...))Walk calls fn for this frame and every frame below it, parents before their children, in the order the frames appear in their documents. It stops as soon as fn returns false.
| fn | func(...) |
frames, _ := page.Frames(ctx)
frames.Walk(func(f *browserscale.FrameInfo, depth int) bool {
fmt.Println(strings.Repeat(" ", depth), f.Url, f.Name)
return true
})NetworkCapture
4 methodsNetworkCapture is a running capture, returned by CloudBrowser.CaptureNetwork. Exchanges are delivered to the handler passed there; this handle only exists to stop the capture and to report how it went.
Dropped
method on NetworkCaptureDropped() → uint64Dropped reports how many exchanges the server discarded because this reader fell behind. Anything above zero means the log has holes: make the handler cheaper or narrow Patterns.
uint64Err
method on NetworkCaptureErr()Err reports why the capture ended. It returns nil while the capture is still running, and after a clean stop, a cancelled context, or the session ending normally.
Stop
method on NetworkCaptureStop()Stop ends the capture. Idempotent, and safe to defer.
Once it returns, the handler is no longer running and everything it wrote is visible to the calling goroutine — so a handler may append to a slice without locking, as long as you only read that slice after Stop. Views from CloudBrowser.StreamNetworkExchanges only detach — they never disarm a capture other readers may share.
To stop from inside the handler, call CloudBrowser.StopNetworkCapture instead: Stop waits for the handler to return, so calling it from there would wait on itself until ctx expires.
ctx covers the disarm call, so pass a live one: the context the capture was created with may already be cancelled by the time you stop.
Reports only transport failures, and the local reader is shut down regardless. Disarming a capture that is not running is a no-op rather than a failure, so there are no error codes to branch on.
Wait
method on NetworkCaptureWait()Wait blocks until the capture ends — NetworkCapture.Stop, a cancelled context, a dead session or a transport failure — and returns NetworkCapture.Err.
Use it to capture for as long as the session lives. It is not needed when you drive the browser yourself and call Stop when done.
Page
58 methodsPage is one page (tab or popup) of the browser. Everything that acts on a document — navigating, waiting, clicking, typing, reading — is a Page method.
A Page is only the page's id: it holds no state and asks for none, so it never goes stale on its own. Which pages exist and which has the focus is the browser's to know. When the page closes, its next call fails with a PageClosedError that names the page that has the focus now.
A browser starts without a page: CloudBrowser.CreatePage opens the first. Get one from CloudBrowser.CreatePage, CloudBrowser.FocusedPage, CloudBrowser.Pages or CloudBrowser.GetPage.
AddReaction
method on PageAddReaction(match *Locator) → stringAddReaction registers a one-shot "reaction": the browser watches for the match locator in the background and, as soon as it matches, clicks it the same way Page.Click does (scroll, human path, occlusion check) — then removes itself. When it fires, the input action you are running pauses at a safe point (a click before it presses, a fill between two keys), the reaction clicks, and the action carries on within its own timeout — e.g. it dismisses a newsletter modal blocking a Page.Click, and the click then lands. A captcha solve takes the page first, a button held down by a press-only click keeps reactions out until its release, and a reaction waits for its page to have the focus. A reaction added here belongs to this page and is torn down automatically when the page/session ends; use CloudBrowser.AddReaction for one that covers every page. Each click is reported as a ContextEventReactionFired on CloudBrowser.ContextEvents.
match must be a CSS or JS Locator — a reference and At are rejected. A CSS match is watched for on the whole page, every frame included, the ones that appear later too; a JS match runs in the main document. Use Locator.In to watch one frame or one part of the page instead, and Locator.Visible(false) to opt out of the default visibility gate.
| match | *Locator | the CSS/JS locator to watch for |
// Auto-dismiss a consent button whenever it appears, in any frame.
id, err := page.AddReaction(ctx, browserscale.CSS("button#accept"))
if err != nil {
log.Fatal(err)
}
_ = id// Only the one inside the consent provider's iframe.
cmp := browserscale.FrameURL("*consent.example.com/*")
id, err := page.AddReaction(ctx, browserscale.CSS("button.accept").In(cmp))stringthe reactionId (pass to Page.RemoveReaction)AddReactionWith(match *Locator, opts ReactionOpts) → stringAddReactionWith is the customizable variant of Page.AddReaction.
match must be a CSS or JS Locator — a reference and At are rejected. A CSS match is watched for on the whole page, every frame included, the ones that appear later too; a JS match runs in the main document. Use Locator.In to watch one frame or one part of the page instead, and Locator.Visible(false) to opt out of the default visibility gate.
| match | *Locator | the CSS/JS locator to watch for |
| opts | ReactionOpts | reaction customization; see ReactionOpts |
// Watch for a newsletter modal, but click its close "X" instead.
id, err := page.AddReactionWith(ctx,
browserscale.CSS("#newsletter-modal"),
browserscale.ReactionOpts{On: browserscale.CSS(".modal-close")},
)stringthe reactionId (pass to Page.RemoveReaction)Browser
method on PageBrowser() → *CloudBrowserBrowser is the browser the page belongs to.
Click
method on PageClick(target *Locator) → *ElementResultClick triggers a single left mouse click on the given target.
The element does not have to be ready when you call this. For up to 5s the browser keeps re-locating it, scrolls it into view, waits for its bounds to hold still for 750ms, and hit-tests the exact point it is about to press — so a plain Click also does the work of a preceding Page.Wait, and needs no retry loop of your own. If the element never settles within that budget the click is attempted at the deadline rather than abandoned.
If something covers the target, the pointer is repositioned once to an exposed part of it, which also gives hover-triggered overlays a chance to collapse. Only if the target is still covered afterwards does the click refuse — it never presses whatever happens to lie on top.
The cursor then moves along a human-like path rather than jumping, and a full mouseDown+mouseUp is dispatched at a randomized point inside the element's bounding rect.
| target | *Locator | locator describing what to click; At is also valid |
res, err := page.Click(ctx, browserscale.CSS("button.submit"))
if err != nil {
var ce *browserscale.ClickError
if errors.As(err, &ce) {
log.Printf("blocked by %s (%s)", ce.Occluder.TagName, ce.Code)
}
log.Fatal(err)
}*ElementResult*ElementResult with success, the element's Ref and Frame,| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
ClickWith(target *Locator, opts ClickOpts) → *ElementResultClickWith is the customizable variant of Page.Click.
The element does not have to be ready when you call this. For up to 5s the browser keeps re-locating it, scrolls it into view, waits for its bounds to hold still for 750ms, and hit-tests the exact point it is about to press — so a plain Click also does the work of a preceding Page.Wait, and needs no retry loop of your own. If the element never settles within that budget the click is attempted at the deadline rather than abandoned.
If something covers the target, the pointer is repositioned once to an exposed part of it, which also gives hover-triggered overlays a chance to collapse. Only if the target is still covered afterwards does the click refuse — it never presses whatever happens to lie on top.
The cursor then moves along a human-like path rather than jumping, and a full mouseDown+mouseUp is dispatched at a randomized point inside the element's bounding rect.
| target | *Locator | locator describing what to click; At is also valid |
| opts | ClickOpts | click customization; see ClickOpts |
// Right double-click on a context menu trigger.
_, err := page.ClickWith(ctx, browserscale.CSS("li.menu"), browserscale.ClickOpts{
Button: "right",
ClickCount: 2,
})*ElementResult*ElementResult with success, the element's Ref and Frame,| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
Close
method on PageClose() → *PageClose closes the page the way closing its tab does. Its unload handlers run, but no "leave site?" prompt is shown. Returns once the page is gone.
page, err = popup.Close(ctx)
if err != nil {
log.Fatal(err)
}*Page*Page the page that has the focus afterwards; when the closed pageDragBy
method on PageDragBy(target *Locator, offsetX float64, offsetY float64) → *DragResultDragBy picks up the target and drops it at an offset relative to the pickup point.
The source is acquired with the same smart click as Page.Click — re-located, scrolled into view, settled and hit-tested — so the handle does not have to be ready when you call this. The browser then presses the left mouse button at a point inside the element, drags along a human-like path to (pickupX+offsetX, pickupY+offsetY), and releases. At is not a valid target — drag needs a real element.
| target | *Locator | locator describing the element to pick up |
| offsetX | float64 | horizontal distance to drag, in CSS pixels |
| offsetY | float64 | vertical distance to drag, in CSS pixels |
_, err := page.DragBy(ctx, browserscale.CSS(".slider .handle"), 120, 0)
if err != nil {
log.Fatal(err)
}*DragResult*DragResult with the the element's Ref and Frame and the| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
DragTo
method on PageDragTo(target *Locator, absoluteX float64, absoluteY float64) → *DragResultDragTo picks up the target and drops it at absolute root-viewport coordinates.
Same gesture and same source acquisition as Page.DragBy, but the drop destination is in page coordinates rather than relative to the pickup point.
| target | *Locator | locator describing the element to pick up |
| absoluteX | float64 | horizontal drop coordinate in the root viewport |
| absoluteY | float64 | vertical drop coordinate in the root viewport |
_, err := page.DragTo(ctx, browserscale.CSS(".card"), 800, 400)
if err != nil {
log.Fatal(err)
}*DragResult*DragResult with the the element's Ref and Frame and the| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
Evaluate
method on PageEvaluate(expression string) → *EvaluateResultEvaluate runs a JavaScript expression in the page's main frame.
The expression's return value is JSON-serialized server-side and parsed eagerly into EvaluateResult.Value. When the expression returns a DOM element the EvaluateResult.Value is left empty and the element metadata (Ref, IsVisible, Bounds) is populated instead — pass the Ref to subsequent calls to act on it.
A promise is waited for: the call returns when it settles, with the value it resolved to, and a rejected one comes back as a *CommandError with the code "threw". The wait ends after 30s with "timeout"; Page.EvaluateWith sets another time, or starts the promise without waiting. The expression may use await directly. It then runs as the body of an async function: a single expression is the value, several statements end with return.
The page sees nothing of the expression: what it throws is not reported to the page's error handling, and a promise is watched without subscribing to it.
A falsy answer and a broken expression are different outcomes. Returning null, false or undefined is a successful evaluation and comes back as a result; an expression that throws or will not compile comes back as a *CommandError, so a typo can never read as "the page says null".
| expression | string | JavaScript expression evaluated in the main frame |
res, err := page.Evaluate(ctx, "document.title")
if err != nil {
log.Fatal(err)
}
fmt.Println(res.Value)// A promise is waited for; await works as well.
items, err := page.Evaluate(ctx, "fetch('/api/items').then(r => r.json())")
count, err := page.Evaluate(ctx, "(await (await fetch('/api/items')).json()).length")// Telling a false answer from a broken expression.
res, err := page.Evaluate(ctx, "window.__ready === true")
var ce *browserscale.CommandError
if errors.As(err, &ce) {
log.Fatalf("expression is broken: %v", ce)
}
if res.Value != true {
// legitimately not ready yet
}*EvaluateResult*EvaluateResult with either Value (for non-Element returns) orEvaluateIn(container *Locator, expression string) → *EvaluateResultEvaluateIn runs a JavaScript expression inside a container: in the document of a frame, or scoped to an element.
Same semantics as Page.Evaluate, but the expression runs where the container leads:
- a frame (FrameURL, FrameName, FrameByID, or a CSS, JS or reference locator naming an iframe element): that frame's document, same-origin or not - any other element: the document the element lives in, with the element itself available to the expression as __wrc.scope
The container is looked up once, as the page is at that moment; it does not wait for a frame that is still to come. Use Page.Wait first when it may not be there yet. The result's Frame says which frame the expression ran in.
| container | *Locator | where the expression runs; see Locator.In |
| expression | string | JavaScript expression evaluated in the main frame |
pay := browserscale.CSS("iframe[title='Secure payment']")
title, err := page.EvaluateIn(ctx, pay, "document.title")// Scoped to an element: how many rows does this table have?
table := browserscale.CSS("table#orders")
rows, err := page.EvaluateIn(ctx, table, "__wrc.scope.rows.length")*EvaluateResult*EvaluateResult with either Value (for non-Element returns) or| StaleRefError | the container is a reference whose element is gone |
EvaluateWith(expression string, opts EvaluateOpts) → *EvaluateResultEvaluateWith is the customizable variant of Page.Evaluate and Page.EvaluateIn.
The expression's return value is JSON-serialized server-side and parsed eagerly into EvaluateResult.Value. When the expression returns a DOM element the EvaluateResult.Value is left empty and the element metadata (Ref, IsVisible, Bounds) is populated instead — pass the Ref to subsequent calls to act on it.
A promise is waited for: the call returns when it settles, with the value it resolved to, and a rejected one comes back as a *CommandError with the code "threw". The wait ends after 30s with "timeout"; Page.EvaluateWith sets another time, or starts the promise without waiting. The expression may use await directly. It then runs as the body of an async function: a single expression is the value, several statements end with return.
The page sees nothing of the expression: what it throws is not reported to the page's error handling, and a promise is watched without subscribing to it.
A falsy answer and a broken expression are different outcomes. Returning null, false or undefined is a successful evaluation and comes back as a result; an expression that throws or will not compile comes back as a *CommandError, so a typo can never read as "the page says null".
| expression | string | JavaScript expression evaluated in the main frame |
| opts | EvaluateOpts | where the expression runs, how long a promise is waited for, or that it is not waited for; see EvaluateOpts |
// A report that takes longer than the default 30s.
res, err := page.EvaluateWith(ctx, "buildReport()", browserscale.EvaluateOpts{TimeoutMs: 120000})
var ce *browserscale.CommandError
if errors.As(err, &ce) && ce.Code == "timeout" {
// still running in the page; only the call gave up
}// Start work and come back to it: the call returns at once.
_, err := page.EvaluateWith(ctx, "window.job = crawl(urls)", browserscale.EvaluateOpts{NoAwait: true})
// ... other steps ...
rows, err := page.EvaluateWith(ctx, "window.job", browserscale.EvaluateOpts{TimeoutMs: 300000})*EvaluateResult*EvaluateResult with either Value (for non-Element returns) or| StaleRefError | opts.In is a reference whose element is gone |
Fill
method on PageFill(target *Locator, text string) → *ElementResultFill clicks the target and types text into it, appending to any existing content.
The field is acquired with the same smart click as Page.Click: re-located, scrolled into view, settled and hit-tested within the timeout budget, so it does not have to be present or ready yet. The cursor then moves along a human-like path and clicks to focus.
Typing is per-key rather than a value assignment: keyDown, char and keyUp for every character, with the keycodes of the layout that matches the session's region and human cadence between them. If the field already holds text the caret is moved to the end first, so appended input lands after the existing content instead of wherever the caret happened to sit.
Fill is strictly target-bound. If something else takes focus mid-typing, the remaining characters are never typed into the thief — the browser tries to re-focus the target and otherwise fails with "focus_stolen", naming the element that holds focus instead so you can deal with it (a consent button, a different field). For stream-style typing that is *supposed* to move between fields, such as an OTP input that auto-advances, use Page.Type instead.
To overwrite the field instead of appending, use Page.FillWith with ClearFirst: true.
At is not a valid target — Fill requires an actual element.
| target | *Locator | locator describing the input element |
| text | string | text to type into the element |
res, err := page.Fill(ctx, browserscale.CSS("input[name=email]"), "user@example.com")
if err != nil {
var fe *browserscale.FillError
if errors.As(err, &fe) && fe.ClickError != nil {
log.Printf("blocked by %s", fe.ClickError.Occluder.TagName)
}
log.Fatal(err)
}
_ = res*ElementResult*ElementResult with success, the element's Ref and Frame| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
FillWith(target *Locator, text string, opts FillOpts) → *ElementResultFillWith is the customizable variant of Page.Fill.
The field is acquired with the same smart click as Page.Click: re-located, scrolled into view, settled and hit-tested within the timeout budget, so it does not have to be present or ready yet. The cursor then moves along a human-like path and clicks to focus.
Typing is per-key rather than a value assignment: keyDown, char and keyUp for every character, with the keycodes of the layout that matches the session's region and human cadence between them. If the field already holds text the caret is moved to the end first, so appended input lands after the existing content instead of wherever the caret happened to sit.
Fill is strictly target-bound. If something else takes focus mid-typing, the remaining characters are never typed into the thief — the browser tries to re-focus the target and otherwise fails with "focus_stolen", naming the element that holds focus instead so you can deal with it (a consent button, a different field). For stream-style typing that is *supposed* to move between fields, such as an OTP input that auto-advances, use Page.Type instead.
To overwrite the field instead of appending, use Page.FillWith with ClearFirst: true.
At is not a valid target — Fill requires an actual element.
| target | *Locator | locator describing the input element |
| text | string | text to type into the element |
| opts | FillOpts | fill customization; see FillOpts |
// Wipe the field first, then type fresh content.
_, err := page.FillWith(ctx, browserscale.CSS("input[name=email]"), "user@example.com", browserscale.FillOpts{
ClearFirst: true,
})*ElementResult*ElementResult with success, the element's Ref and Frame| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
Focus
method on PageFocus()Focus brings the page to the front, the way clicking its tab does: it becomes visible, and the page it replaces is hidden. Focusing the page that already has the focus changes nothing.
if err := page.Focus(ctx); err != nil {
log.Fatal(err)
}| PageClosedError | the page has closed |
FollowScript
method on PageFollowScript(runId string, onEvent ScriptEventHandler) → *ScriptFollowFollowScript watches script output on the page without starting anything.
For the case Page.StartScript cannot cover: a run somebody else launched, or one this process started before it restarted. Several readers can watch the same page, each with its own buffer.
Only output produced from now on arrives — lines printed before the subscription existed are not kept. A run that has already finished is therefore invisible here; Page.ListScriptRuns is how you tell that apart from a run that is merely quiet.
| runId | string | run to follow, or "" to follow every run on the page |
| onEvent | ScriptEventHandler | called per event; see ScriptEventHandler for the ordering |
follow, err := page.FollowScript(ctx, runId, func(ev browserscale.ScriptEvent) {
if ev.Log != nil { fmt.Println(ev.Log.Message) }
})
if err != nil { log.Fatal(err) }
defer follow.Stop()*ScriptFollow*ScriptFollow handle for stopping the subscriptionFrames
method on PageFrames() → *FrameInfoFrames returns the page's frame tree: the main frame, and below it every iframe, nested the way the documents are.
Each FrameInfo says what a frame shows (URL, name), where it sits and whether a person can see it. It is for looking around: to find out which frames a page has, and what would tell one from the others in a FrameURL or FrameName. To act in a frame straight away, FrameInfo.Locator hands it back as a container.
A frame is not an element, so the tree carries no reference to the iframe elements. Where the iframe element itself is needed (to click or scroll it), name it with CSS or take it from Page.Wait.
frames, err := page.Frames(ctx)
if err != nil {
log.Fatal(err)
}
frames.Walk(func(f *browserscale.FrameInfo, depth int) bool {
fmt.Printf("%s%s name=%q visible=%v\n", strings.Repeat(" ", depth), f.Url, f.Name, f.IsVisible)
return true
})*FrameInfo*FrameInfo of the main frame, with its Children| PageClosedError | the page has closed |
GetDOM
method on PageGetDOM(frameId string, depth int32) → stringGetDOM returns a JSON string in CDP DOM.Node shape for the requested frame.
The shape matches Chrome DevTools' Protocol DOM.Node — useful for piping into agent loops or visualizers that already speak CDP. For a much smaller agent-oriented payload, prefer Page.GetObservation instead.
| frameId | string | id of the frame to dump; empty targets the main frame |
| depth | int32 | tree depth: -1 for the full tree, 0 for root only, N for |
tree, err := page.GetDOM(ctx, "", -1)
if err != nil {
log.Fatal(err)
}
fmt.Println(tree)stringJSON string in CDP DOM.Node shapeGetDomChildren
method on PageGetDomChildren(backendNodeId int32, frameId string, depth int32) → *DomChildrenGetDomChildren fetches a node's children and starts reporting changes inside them. DomMirror.Expand calls this and folds the result into the tree.
On an <iframe>/<frame>/<object> the one child is the document it hosts, and this call is what starts mirroring that frame.
| backendNodeId | int32 | the node to open |
| frameId | string | the frame its id belongs to; empty targets the main frame |
| depth | int32 | levels below the node; 0 uses the server default of 1 |
*DomChildren*DomChildren with the child list as JSON and the sequence it isGetDOMHash
method on PageGetDOMHash(frameId string) → stringGetDOMHash returns sha256:8 of the full-tree DOM JSON for cheap polling-based change detection.
Computing a hash is much cheaper than transferring the full tree — pair this with Page.GetDOM only when the hash differs from your last snapshot.
| frameId | string | id of the frame to hash; empty targets the main frame |
hash, err := page.GetDOMHash(ctx, "")
if err != nil {
log.Fatal(err)
}
if hash != lastHash {
// DOM changed → re-fetch
}string16-char hex string (the first 8 bytes of sha256 of the DOM JSON)GetDomRevision
method on PageGetDomRevision(frameId string) → uint64GetDomRevision returns a frame's mutation counter, incremented on every change the document sees. O(1) in the browser and the change detector to poll if you are not consuming mirror events.
Prefer it over Page.GetDOMHash, which serializes the whole tree just to hash it. The two answer different questions: a hash compares content, a revision only says whether this document moved since you last asked. The counter is meaningful only within the current document.
| frameId | string | the frame to ask; empty targets the main frame |
uint64uint64 monotonic counterGetObservation
method on PageGetObservation() → stringGetObservation returns a compact, frame-aware view of the visible page — the first thing to reach for on an unfamiliar page, and the cheapest way to re-read the current state afterwards.
Each frame opens with header lines carrying the URL, the title and the scroll position, then one line per element a person can see or act on:
input#email47 type="email" name="loginId" value="a@b.com" required click "E-Mail"
It spans every frame, pierces open and closed shadow roots, enumerates <select> options, and reports live state: value= is what is typed in right now (passwords as a length), checked= for boxes, expanded= for menus and accordions, and flags such as selected, focused, disabled or invalid. The trailing quoted string is always the label or text, never the value, so an empty and a prefilled field stay distinguishable. An element that cannot be seen is listed only when it is interactive, with the reason as hidden="...". When a dialog or a consent layer lies over the page, a header line "# on top: ..." names it, and its rows carry the flag on-top. Because the headers already carry URL, title and scroll offset, this replaces the usual handful of Page.Evaluate probes after each step.
On what to do with the result: each frame's header carries a line "# ref @<document>", and a row's number (the 47 above) followed by that suffix is the element's reference: pass it to click/fill via Ref. It is a handle for this session and does not survive a new document, so for anything you write into a script, target with CSS or JS instead — those calls return the reference they resolved to, which lets you confirm the durable anchor hits the element you saw.
obs, err := page.GetObservation(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(obs)stringthe observation in the requested format, ready to hand to a modelGetObservationWith(opts ObservationOpts) → stringGetObservationWith is the customizable variant of Page.GetObservation.
Each frame opens with header lines carrying the URL, the title and the scroll position, then one line per element a person can see or act on:
input#email47 type="email" name="loginId" value="a@b.com" required click "E-Mail"
It spans every frame, pierces open and closed shadow roots, enumerates <select> options, and reports live state: value= is what is typed in right now (passwords as a length), checked= for boxes, expanded= for menus and accordions, and flags such as selected, focused, disabled or invalid. The trailing quoted string is always the label or text, never the value, so an empty and a prefilled field stay distinguishable. An element that cannot be seen is listed only when it is interactive, with the reason as hidden="...". When a dialog or a consent layer lies over the page, a header line "# on top: ..." names it, and its rows carry the flag on-top. Because the headers already carry URL, title and scroll offset, this replaces the usual handful of Page.Evaluate probes after each step.
On what to do with the result: each frame's header carries a line "# ref @<document>", and a row's number (the 47 above) followed by that suffix is the element's reference: pass it to click/fill via Ref. It is a handle for this session and does not survive a new document, so for anything you write into a script, target with CSS or JS instead — those calls return the reference they resolved to, which lets you confirm the durable anchor hits the element you saw.
| opts | ObservationOpts | observation customization; see ObservationOpts |
// Only what is on screen right now, as structured JSON.
obs, err := page.GetObservationWith(ctx, browserscale.ObservationOpts{
Format: "json",
ViewportOnly: true,
})
// Re-read just one form after the first full look.
obs, err = page.GetObservationWith(ctx, browserscale.ObservationOpts{
Scope: browserscale.CSS("form#register"),
})
// Only what one frame shows.
obs, err = page.GetObservationWith(ctx, browserscale.ObservationOpts{
Scope: browserscale.FrameURL("*checkout.example.com/*"),
})stringthe observation in the requested format, ready to hand to a modelGetSelection
method on PageGetSelection() → stringGetSelection returns the current text selection.
Walks every frame and returns the first non-empty selection found — useful for "copy what the user highlighted" flows. Returns an empty string when nothing is selected anywhere.
sel, err := page.GetSelection(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("user selected:", sel)stringthe selected text, or "" when nothing is selectedHighlight
method on PageHighlight(ref *Locator)Highlight paints a debug overlay over the element a reference names.
Useful for visual debugging of agent flows: mark what a wait found or what a click is about to hit. At most one element is marked on the whole page; the overlay stays until the next call. Pass nil to clear it. The overlay is drawn by the browser, not by the page: it changes nothing in the document and scripts cannot see it.
| ref | *Locator | the Ref of a result (or Ref for one read from an observation); nil clears the highlight |
res, _ := page.Wait(ctx, browserscale.CSS("button.submit"))
if err := page.Highlight(ctx, res.Element.Ref); err != nil {
log.Fatal(err)
}| StaleRefError | the reference's element is gone |
HighlightNode
method on PageHighlightNode(backendNodeId int32, frameId string)HighlightNode paints a debug overlay over a node of the DOM mirror, identified the way the mirror identifies it: by backendNodeId and frame. For an element a result named, use Page.Highlight with its Ref.
The overlay stays until the next call. Pass backendNodeId <= 0 to clear any current highlights.
| backendNodeId | int32 | id of the node to highlight, or <= 0 to clear |
| frameId | string | id of the frame the node lives in; empty targets the main frame |
if err := page.HighlightNode(ctx, node.BackendNodeId, node.FrameId); err != nil {
log.Fatal(err)
}Id
method on PageId() → stringId is the page's id, stable for the life of the page.
stringInsertText
method on PageInsertText(text string)InsertText pastes text at the current caret using IME-style input.
No individual key events are dispatched; the entire string is committed at once via Input.insertText. Whatever element currently has focus receives the text. Use Page.Click or Page.Fill first if you need a specific element to be focused.
| text | string | the text to insert at the caret |
if err := page.InsertText(ctx, "hello world"); err != nil {
log.Fatal(err)
}InspectAtPosition
method on PageInspectAtPosition(x float64, y float64) → *InspectResultInspectAtPosition hit-tests at the viewport-relative (x, y) and returns the topmost element under that point.
Mirrors what the live-UI overlay does on hover. Elements with pointer-events:none are skipped — the result is the actual click target, not the visually-topmost node.
| x | float64 | viewport-relative x in CSS pixels |
| y | float64 | viewport-relative y in CSS pixels |
res, err := page.InspectAtPosition(ctx, 200, 300)
if err != nil {
log.Fatal(err)
}
fmt.Println(res.TagName, res.TextContent)
if res.Ref != nil {
_, _ = page.Click(ctx, res.Ref) // act on what is under the point
}*InspectResult*InspectResult with the element's Ref and Frame, its address inListReactions
method on PageListReactions() → []ReactionInfoListReactions returns the reactions still pending on the current page, including those from CloudBrowser.AddReaction that have not fired here yet (ReactionInfo.AllPages is set on those). Reactions that have already fired on this page are not included.
pending, err := page.ListReactions(ctx)
for _, r := range pending {
log.Printf("reaction %s watching %s%s", r.ReactionID, r.MatchSelector, r.MatchJsExpression)
}[]ReactionInfothe pending reactions for the pageListScriptRuns
method on PageListScriptRuns() → []ScriptRunInfoListScriptRuns reports the scripts still running on the page.
Only runs in flight — a finished run is reported once on the event stream and then forgotten, so this is not a history. Its use is finding work this caller did not start: a script a previous process left behind, which Page.StopScripts needs an id to name.
runs, err := page.ListScriptRuns(ctx)
if err != nil { log.Fatal(err) }
for _, run := range runs {
fmt.Println(run.RunId, run.Running)
}[]ScriptRunInfo[]ScriptRunInfo one entry per run still executingLoadHTML
method on PageLoadHTML(url string, html string, headers []Header, statusCode int32)LoadHTML navigates the page to url and serves html as the response.
The page navigates as with Page.Navigate, but the request for url never reaches the network: it is answered with the supplied html, headers and status code. The answer is used once; a later navigation to url, also a reload, goes to the network again. Useful for snapshotted pages, test fixtures, and offline replays. It returns once the response was handed to the page, so wait for what the next step needs as after a navigation.
| url | string | the URL the page will show the html under |
| html | string | the response body to serve |
| headers | []Header | extra response headers (Content-Type is set automatically) |
| statusCode | int32 | HTTP status code to serve; 0 means 200 |
_ = page.LoadHTML(ctx, "https://example.com", "<h1>hi</h1>", nil, 0)
_, _ = page.Wait(ctx, browserscale.CSS("h1"))MirrorDom
method on PageMirrorDom(opts DomMirrorOptions, onChange DomChangeHandler, onResync DomResyncHandler) → *DomMirrorMirrorDom starts mirroring the page and returns a live copy of its DOM.
One mirror covers the whole page as ONE tree. An <iframe> is an ordinary element whose single child is the document it hosts; expanding it fetches that document and starts mirroring the frame, however deeply nested and whether or not it is cross-origin. Unlike the inlining Page.GetDOM does, these regions stay live — and frames nobody opened cost nothing.
This replaces polling Page.GetDOMHash and re-fetching GetDOM: the browser reports changes to the part you actually expanded instead of re-serializing the document so you can hash it.
The subscription is established before the snapshot is taken, so no change between the two is lost. Call DomMirror.Stop when done — it stops the mirror server-side, which a cancelled context alone does not.
| opts | DomMirrorOptions | initial depth and whether to pierce shadow roots |
| onChange | DomChangeHandler | called after every change, including the first snapshot; |
| onResync | DomResyncHandler | called when the copy had to be rebuilt; may be nil |
mirror, err := page.MirrorDom(ctx, browserscale.DomMirrorOptions{Pierce: true},
func(m *browserscale.DomMirror) {
render(m.Root())
}, nil)
if err != nil {
log.Fatal(err)
}
defer mirror.Stop(ctx)
body := mirror.Node(mirror.MainFrameId(), bodyId)
_ = mirror.Expand(ctx, body, 0)*DomMirror*DomMirror holding the treeMoveTo
method on PageMoveTo(target *Locator) → *ElementResultMoveTo moves the mouse cursor over the given target.
The browser scrolls the target into view first if necessary, then animates the cursor along a human-like path to the element's random center area (or to the viewport coordinate when target is At).
| target | *Locator | locator describing where to move; At is also valid |
_, err := page.MoveTo(ctx, browserscale.CSS("nav .menu"))
if err != nil {
log.Fatal(err)
}*ElementResult*ElementResult with the the element's Ref and Frame,| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
NodeRef
method on PageNodeRef(backendNodeId int32, frameId string) → *LocatorNodeRef turns the address of a DOM mirror node into a reference that Page.Click, Page.Fill and every other call with a target takes.
The mirror (Page.MirrorDom) and Page.GetDOM name a node by its backendNodeId and the frame it lives in. Actions take a reference instead, which also names the document, so that a node id can never be mistaken for a node of whatever the frame shows next. This is the bridge between the two: the reference names the node in the document its frame shows now. Whether the node still exists is not checked here; a reference made from an outdated id fails with a *StaleRefError when it is used.
| backendNodeId | int32 | the node's DomNode.BackendNodeId |
| frameId | string | the node's DomNode.FrameId; empty is the main frame |
button, err := page.NodeRef(ctx, node.BackendNodeId, node.FrameId)
if err != nil {
log.Fatal(err)
}
_, _ = page.Click(ctx, button)*Locator*Locator naming the node, usable as a target or a containerPressKey
method on PagePressKey(key string, code string, modifiers int32, location int32)PressKey fires a single key-down event.
Only the keydown half is dispatched — pair with Page.ReleaseKey for a full press cycle. The event targets whichever element currently has focus.
| key | string | DOM KeyboardEvent.key value (e.g. "Enter", "a", "ArrowLeft") |
| code | string | DOM KeyboardEvent.code value (e.g. "Enter", "KeyA"); empty falls back to key |
| modifiers | int32 | bit-flag combination: Alt=1, Ctrl=2, Meta=4, Shift=8 |
| location | int32 | DOM KeyboardEvent.location: 0=standard, 1=left, 2=right, 3=numpad |
// Ctrl+A
_ = page.PressKey(ctx, "a", "KeyA", 2, 0)
_ = page.ReleaseKey(ctx, "a", "KeyA", 2, 0)ReadCanvas
method on PageReadCanvas(target *Locator) → *ReadCanvasResultReadCanvas reads the pixels of a <canvas> element directly in the renderer, bypassing the origin-clean (tainted) security check and without executing any page JavaScript — so cross-origin/tainted canvases (common in captchas) read fine where a normal toDataURL / getImageData would throw a SecurityError.
| target | *Locator | locator for the <canvas>; CSS, JS or a reference |
res, err := page.ReadCanvas(ctx, browserscale.CSS("#game canvas"))
if err != nil {
log.Fatal(err)
}
img, _ := base64.StdEncoding.DecodeString(res.DataBase64)
os.WriteFile("canvas.png", img, 0o644)*ReadCanvasResult*ReadCanvasResult with the base64 image in DataBase64, the canvas| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
ReadCanvasWith(target *Locator, opts ReadCanvasOpts) → *ReadCanvasResultReadCanvasWith is the customizable variant of Page.ReadCanvas.
| target | *Locator | locator for the <canvas>; CSS, JS or a reference |
| opts | ReadCanvasOpts | format, quality, and sub-rectangle; see ReadCanvasOpts |
// Read the left half of the canvas as JPEG at quality 80.
res, err := page.ReadCanvasWith(ctx, browserscale.CSS("canvas"),
browserscale.ReadCanvasOpts{Format: "jpeg", Quality: 80, SW: 150, SH: 300})*ReadCanvasResult*ReadCanvasResult with the base64 image in DataBase64, the canvas| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
ReleaseDomSubtree
method on PageReleaseDomSubtree(backendNodeId int32, frameId string)ReleaseDomSubtree stops reporting changes inside a node, and inside any frame below it. DomMirror.Collapse calls this.
Skipping it is not an error, it is a slow leak: the browser's revealed set only grows, and eventually it is no longer filtering anything.
| backendNodeId | int32 | the node to close |
| frameId | string | the frame its id belongs to; empty targets the main frame |
ReleaseKey(key string, code string, modifiers int32, location int32)ReleaseKey fires a single key-up event.
Mirror of Page.PressKey. Same parameter semantics; use this to close a press cycle that was started with PressKey.
| key | string | DOM KeyboardEvent.key value (e.g. "Enter", "a", "ArrowLeft") |
| code | string | DOM KeyboardEvent.code value (e.g. "Enter", "KeyA"); empty falls back to key |
| modifiers | int32 | bit-flag combination: Alt=1, Ctrl=2, Meta=4, Shift=8 |
| location | int32 | DOM KeyboardEvent.location: 0=standard, 1=left, 2=right, 3=numpad |
_ = page.PressKey(ctx, "Shift", "ShiftLeft", 0, 1)
_ = page.ReleaseKey(ctx, "Shift", "ShiftLeft", 0, 1)RemoveReaction
method on PageRemoveReaction(reactionID string) → boolRemoveReaction removes a pending reaction by id. It returns false if the reaction had already fired (one-shot) or was never registered. An id from CloudBrowser.AddReaction is removed from every page; it is the same call as CloudBrowser.RemoveReaction.
| reactionID | string | id returned by Page.AddReaction |
removed, err := page.RemoveReaction(ctx, id)booltrue if a pending reaction with this id existed and was removedRevealDomNode
method on PageRevealDomNode(backendNodeId int32, frameId string) → *DomPathRevealDomNode returns the chain from the main document down to a node, each ancestor with its own children, crossing into frames where it has to and starting the ones it passes through. DomMirror.Reveal calls this and splices it in.
| backendNodeId | int32 | the node to reach |
| frameId | string | the frame its id belongs to; empty targets the main frame |
*DomPath*DomPath with the ancestor chain as JSON and the sequence it isRunScript
method on PageRunScript(source string) → *ScriptResultRunScript runs source on the page and waits for it to finish.
The script runs beside the browser, in a V8 isolate of its own rather than in the page, and reaches the document through the engine: a cross-origin iframe is read as plain contentDocument with no frame ids anywhere, values come back as live objects it can assign to rather than snapshots, an element can be handed straight to browser.click, and the page sees nothing injected. Steps cost microseconds rather than network round trips, so work that is chatty by nature — polling for a selector, walking a list, following pagination — is affordable there. A guide for it is still to come.
This blocks for as long as the script runs, and cannot be bounded: the run id needed to cancel only arrives with the reply. Cancelling ctx abandons the wait but not the run. Use Page.StartScript when the script may outlive the caller's patience, or Page.StopScripts to abandon what is running on the page.
| source | string | JavaScript to execute; its return value comes back as JSON |
result, err := page.RunScript(ctx, `
await browser.navigate("https://example.com");
const items = [];
for (const el of await browser.getDOM().querySelectorAll("h1")) {
items.push(el.textContent);
}
return items;
`)
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Success, result.Result)*ScriptResult*ScriptResult with the return value and the script's whole consoleScreenshot
method on PageScreenshot(format string, quality int32) → *ScreenshotResultScreenshot captures a single image of the page's current frame and returns it as base64-encoded image bytes.
The capture uses a one-shot surface copy (the same mechanism as CDP Page.captureScreenshot), so it is independent of any active live stream and works with both GPU (hardware) and software compositing.
| format | string | "png" (default), "jpeg", or "webp"; pass "" for PNG |
| quality | int32 | encode quality 0-100 for "jpeg"/"webp" (ignored for |
shot, err := page.Screenshot(ctx, "png", 0)
if err != nil {
log.Fatal(err)
}
img, _ := base64.StdEncoding.DecodeString(shot.DataBase64)
os.WriteFile("page.png", img, 0o644)*ScreenshotResult*ScreenshotResult with the base64 image in DataBase64 and theScrollTo
method on PageScrollTo(target *Locator) → *ElementResultScrollTo scrolls the given element into view.
Whatever scroll container is closest to the element does the scrolling — nested scroll containers and out-of-process iframe chains are walked automatically. At is not a valid target here; scrolling needs a real element.
| target | *Locator | locator describing the element to bring into view; |
_, err := page.ScrollTo(ctx, browserscale.CSS("#footer"))
if err != nil {
log.Fatal(err)
}*ElementResult*ElementResult with the the element's Ref and Frame,| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
SelectByIndex
method on PageSelectByIndex(target *Locator, index int32) → *SelectOptionResultSelectByIndex picks the <option> at the zero-based index inside the targeted <select> element.
Sets the option as selected on the targeted <select>, then fires the standard input + change events (unless suppressed via Page.SelectByIndexWith with SelectOpts.NoEvents).
At is not a valid target — Select requires an actual <select> element.
| target | *Locator | locator describing the <select> element |
| index | int32 | zero-based option index |
_, err := page.SelectByIndex(ctx, browserscale.CSS("select#country"), 2)*SelectOptionResult*SelectOptionResult with the resolved selectedIndex,| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
SelectByIndexWith(target *Locator, index int32, opts SelectOpts) → *SelectOptionResultSelectByIndexWith is the customizable variant of Page.SelectByIndex.
Sets the option as selected on the targeted <select>, then fires the standard input + change events (unless suppressed via Page.SelectByIndexWith with SelectOpts.NoEvents).
At is not a valid target — Select requires an actual <select> element.
| target | *Locator | locator describing the <select> element |
| index | int32 | zero-based option index |
| opts | SelectOpts | select customization; see SelectOpts |
// Pick the option silently, no input/change events.
_, err := page.SelectByIndexWith(ctx, browserscale.CSS("select#hidden"), 0, browserscale.SelectOpts{
NoEvents: true,
})*SelectOptionResult*SelectOptionResult with the resolved selectedIndex,| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
SelectByText(target *Locator, text string) → *SelectOptionResultSelectByText picks the <option> whose visible (trimmed) text matches the given string exactly.
Sets the option as selected on the targeted <select>, then fires the standard input + change events (unless suppressed via Page.SelectByIndexWith with SelectOpts.NoEvents).
At is not a valid target — Select requires an actual <select> element.
| target | *Locator | locator describing the <select> element |
| text | string | the visible option text to match |
_, err := page.SelectByText(ctx, browserscale.CSS("select#country"), "Germany")*SelectOptionResult*SelectOptionResult with the resolved selectedIndex,| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
SelectByTextWith(target *Locator, text string, opts SelectOpts) → *SelectOptionResultSelectByTextWith is the customizable variant of Page.SelectByText.
Sets the option as selected on the targeted <select>, then fires the standard input + change events (unless suppressed via Page.SelectByIndexWith with SelectOpts.NoEvents).
At is not a valid target — Select requires an actual <select> element.
| target | *Locator | locator describing the <select> element |
| text | string | the visible option text to match |
| opts | SelectOpts | select customization; see SelectOpts |
_, err := page.SelectByTextWith(ctx, browserscale.CSS("select#country"), "Germany", browserscale.SelectOpts{
NoEvents: true,
})*SelectOptionResult*SelectOptionResult with the resolved selectedIndex,| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
SelectByValue(target *Locator, value string) → *SelectOptionResultSelectByValue picks the <option> whose value attribute matches the given string exactly.
Sets the option as selected on the targeted <select>, then fires the standard input + change events (unless suppressed via Page.SelectByIndexWith with SelectOpts.NoEvents).
At is not a valid target — Select requires an actual <select> element.
| target | *Locator | locator describing the <select> element |
| value | string | the value attribute to match |
_, err := page.SelectByValue(ctx, browserscale.CSS("select#country"), "DE")*SelectOptionResult*SelectOptionResult with the resolved selectedIndex,| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
SelectByValueWith(target *Locator, value string, opts SelectOpts) → *SelectOptionResultSelectByValueWith is the customizable variant of Page.SelectByValue.
Sets the option as selected on the targeted <select>, then fires the standard input + change events (unless suppressed via Page.SelectByIndexWith with SelectOpts.NoEvents).
At is not a valid target — Select requires an actual <select> element.
| target | *Locator | locator describing the <select> element |
| value | string | the value attribute to match |
| opts | SelectOpts | select customization; see SelectOpts |
_, err := page.SelectByValueWith(ctx, browserscale.CSS("select#country"), "DE", browserscale.SelectOpts{
NoEvents: true,
})*SelectOptionResult*SelectOptionResult with the resolved selectedIndex,| StaleRefError | the target or a container is a reference whose element is gone (code "stale_ref") |
SolveCaptcha
method on PageSolveCaptcha(timeoutMs int32, retryAmount int32) → stringSolveCaptcha detects and solves the first supported bot-challenge it finds anywhere on the page.
Detection covers the common challenge types you run into in the wild. The challenge is detected and solved in the live browser session — no page scripting, no external service — and the result is wired back into the page automatically, so callers can ignore the returned string.
One captcha is solved at a time per page: if auto-solve (CloudBrowser.EnableCaptchaAutoSolve) is already solving one there, the call waits for that solve and returns its outcome instead of starting a second one. Like an auto-solve, the solve holds the actions running on the page and is reported on CloudBrowser.ContextEvents (Trigger "command").
| timeoutMs | int32 | how long to wait for a captcha to appear, in |
| retryAmount | int32 | number of retries on a failed solve before giving up |
if _, err := page.SolveCaptcha(ctx, 0, 2); err != nil {
var ce *browserscale.SolveCaptchaError
if errors.As(err, &ce) && ce.Code == "blocked" {
// start over in a fresh session
}
log.Fatal(err)
}stringempty string on success — the solution is applied server-sideStartDomMirror
method on PageStartDomMirror(opts DomMirrorOptions) → *DomSnapshotStartDomMirror starts (or restarts) the page's mirror and returns the main document, without subscribing to changes. Page.MirrorDom is what you normally want; this is the raw command.
Calling it again restarts the mirror, which is also the recovery path after a resync. Subscribe before calling it: changes between the snapshot and the subscription are not replayed.
| opts | DomMirrorOptions | initial depth and whether to pierce shadow roots |
*DomSnapshot*DomSnapshot with the main document, its frame and the baselineStartScript
method on PageStartScript(source string, onEvent ScriptEventHandler) → *ScriptRunStartScript launches source on the page and returns as soon as the run is under way.
The counterpart to Page.RunScript, for scripts that are not worth waiting on: a watcher that runs for the life of the session, work that should survive this process. Output arrives at onEvent while the caller gets on with something else, and ScriptRun.Wait collects the outcome if it is wanted.
Subscribing has to happen before the launch, because a detached run's output is not kept anywhere — the browser rejects a start with nobody listening rather than discard the script's log and result. This call does both in that order, so nothing the script prints is missed.
| source | string | JavaScript to execute |
| onEvent | ScriptEventHandler | called per log line and once for the outcome; see |
run, err := page.StartScript(ctx, source, func(ev browserscale.ScriptEvent) {
if ev.Log != nil {
fmt.Println(ev.Log.Level, ev.Log.Message)
}
})
if err != nil {
log.Fatal(err)
}
outcome, err := run.Wait(ctx)*ScriptRun*ScriptRun handle for awaiting or cancelling the runStopDomMirror
method on PageStopDomMirror()StopDomMirror stops the page's mirror, every frame of it. Idempotent.
Reports only transport failures - a dead session, a page that is gone, a broken connection. Stopping a mirror that is not running is a no-op rather than a failure, so there are no error codes to branch on.
StopScripts
method on PageStopScripts(runId string) → intStopScripts cancels runs on the page and reports how many it ended.
An empty runId cancels every run on the page, which is the only form available to a caller that never learned an id — notably one abandoning a blocking Page.RunScript.
| runId | string | run to cancel, or "" for all of them |
_, err := page.StopScripts(ctx, "") // abandon everything runningintint how many runs were cancelled; 0 when the id named nothing inType
method on PageType(text string, clearFirst bool)Type types text into the currently focused element as a per-key stream of real keyboard events (keyDown/char/keyUp on the keyboard layout of the session's region, with human cadence) — unlike Page.InsertText, a single IME-style commit with no key events.
Type is intentionally UNtargeted and loose: it does not locate or focus any element and does NOT pin focus, so the page is free to route keys and move focus between fields mid-stream — ideal for one-time-code / OTP inputs that auto-advance to the next box on each digit. To type one specific field that must stay focused for the whole value, use Page.Fill instead (strict, target-bound, per-key focus-verified).
Nothing is focused for you: Page.Click (or Fill) the field first, or otherwise ensure focus, before calling Type.
| text | string | the text to type as real key events |
| clearFirst | bool | when true, clears the focused field (Ctrl+A, Delete) first |
// OTP field that auto-advances across boxes.
_, _ = page.Click(ctx, browserscale.CSS("input.otp-0"))
if err := page.Type(ctx, "123456", false); err != nil {
log.Fatal(err)
}Wait
method on PageWait(args ...WaitArg) → *WaitResultWait blocks until any of the supplied conditions matches.
Conditions can be mixed freely and are watched in parallel; the first one to match wins and the others are abandoned: - CSS / JS — an element (or a truthy expression) - Captcha — a supported captcha or bot-protection challenge - Request / Response — a network request or its response
Element and captcha conditions are states: they match if the page already is (or becomes) in that state. Request and response conditions are events: only what happens after the wait started counts. A wait does not block the page, so start it before the action that should trigger the event — run it in a goroutine alongside Click, SolveCaptcha or Navigate.
Every condition looks where its own locator says, whatever the others say: a CSS condition on the whole page with every frame, a JS condition in the main document, and either one inside the container given with Locator.In. A condition inside a frame that is not there yet waits for the frame as well. The result names the frame the match was found in.
Anything left unset is defaulted by the API, not by this SDK: - timeout: 30s — override with Timeout - per-locator visible and steady: visibility required, 500ms of settling. For JS expressions returning a non-Element value (bool/string/number/ object) both are no-ops. Override with Locator.Visible / Locator.Steady on individual locators.
A reference and At are not valid wait conditions — they only make sense as action targets — and produce an error at send time.
| args | ...WaitArg | one or more conditions plus optional wait-level options; |
// Whatever comes first: the inbox, a captcha, or the error page.
res, err := page.Wait(ctx,
browserscale.CSS("#inbox"),
browserscale.Captcha(),
browserscale.Request("https://example.com/error*"),
browserscale.Timeout(60000),
)
if err != nil {
log.Fatal(err)
}
switch res.Kind {
case browserscale.WaitKindElement:
_, _ = page.Click(ctx, res.Element.Ref)
case browserscale.WaitKindCaptcha:
_, _ = page.SolveCaptcha(ctx, 0, 2)
case browserscale.WaitKindRequest:
log.Println("failed:", res.Request.Url)
}// Each condition with its own place to look.
pay := browserscale.CSS("iframe[title='Secure payment']")
res, err := page.Wait(ctx,
browserscale.CSS("#order-confirmed"), // whole page
browserscale.CSS(".card-error").In(pay), // only the payment frame
browserscale.JS("location.pathname === '/declined'"), // the top document
browserscale.Captcha(), // whole page
)// Start the wait first, then trigger the request it waits for.
done := make(chan *browserscale.WaitResult, 1)
go func() {
res, _ := page.Wait(ctx, browserscale.Response("https://example.com/api/login*"))
done <- res
}()
_, _ = page.Click(ctx, browserscale.CSS("button[type=submit]"))
if res := <-done; res != nil && res.Response != nil {
fmt.Println(res.Response.StatusCode)
}*WaitResult*WaitResult for the first matching condition: its Index (inPageNotFocusedError
1 methodPageNotFocusedError is returned by Page.Click, Page.MoveTo and the calls built on them (Page.Fill, Page.DragBy, Page.DragTo) when the page does not have the focus, typically because it opened a tab or popup that came to the front. FocusedPage is that page; Page.Focus brings this one back.
It wraps the call's own error (ClickError, MoveError, FillError, DragError), which errors.As still finds.
| FocusedPage? | *Page | FocusedPage is the page that has the focus. |
Unwrap
method on PageNotFocusedErrorUnwrap()Unwrap returns the call's own error.
RequestCondition
1 methodRequestCondition is the wait condition built by Request. It is accepted by Page.Wait only.
Abort
method on RequestConditionAbort(v bool) → *RequestConditionAbort drops the matching request: it is not sent, and the page receives an empty 200 instead. The request is still returned in the WaitResult.
| v | bool | true to drop the request, false to only observe it (the default) |
_, _ = page.Wait(ctx, browserscale.Request("https://tracker.example.com/*").Abort(true))*RequestConditionthe same RequestCondition for chainingResponseCondition
1 methodResponseCondition is the wait condition built by Response. It is accepted by Page.Wait only.
Abort
method on ResponseConditionAbort(v bool) → *ResponseConditionAbort hides the matching response from the page: it receives an empty 200 instead. The real response is still returned in the WaitResult.
| v | bool | true to hide the response, false to pass it through (the default) |
_, _ = page.Wait(ctx, browserscale.Response("https://example.com/api/token*").Abort(true))*ResponseConditionthe same ResponseCondition for chainingScriptFollow
4 methodsScriptFollow is a read-only view of script output, returned by Page.FollowScript.
Dropped
method on ScriptFollowDropped() → uint64Dropped reports how many events the server discarded because this reader fell behind.
uint64Err
method on ScriptFollowErr()Err reports why the subscription ended, or nil while it is still open and after a clean stop.
Stop
method on ScriptFollowStop()Stop ends the subscription. Idempotent, and safe to defer. It never cancels a run: other readers, and the script itself, are unaffected.
Once it returns, the handler is no longer running and everything it wrote is visible to the calling goroutine.
Wait
method on ScriptFollowWait()Wait blocks until the subscription ends — ScriptFollow.Stop, a cancelled context, a dead session or a transport failure — and returns ScriptFollow.Err.
ScriptRun
6 methodsScriptRun is a script running in the background, returned by Page.StartScript. Its output is delivered to the handler passed there; this handle exists to wait for the outcome and to cancel the run.
Detach
method on ScriptRunDetach()Detach stops reading this run's output without cancelling the run. The script keeps going with nobody watching, which is what makes a detached run outlive the process that started it.
Dropped
method on ScriptRunDropped() → uint64Dropped reports how many events the server discarded because this reader fell behind. Anything above zero means the log has holes: make the handler cheaper, or have the script print less.
uint64Err
method on ScriptRunErr()Err reports why the stream ended, or nil while it is still open and after a clean stop, a cancelled context, or the session ending normally.
RunId
method on ScriptRunRunId() → stringRunId is the id the browser gave this run. Pass it to Page.StopScripts to cancel the run from elsewhere, or to Page.FollowScript to watch it from another process.
stringStop
method on ScriptRunStop()Stop cancels the run and detaches this reader. Idempotent, and safe to defer.
A script that is executing is interrupted; one parked on an await unwinds at its next operation in the page. Either way the handler sees a Finished with Stopped set, unless the local reader is torn down first.
ctx covers the cancel call, so pass a live one: the context the run was started with may already be cancelled by the time you stop.
Reports only transport failures, and the local reader is detached regardless. Cancelling a run that has already finished is a no-op rather than a failure.
Wait
method on ScriptRunWait() → *ScriptFinishedWait blocks until the run ends and returns how it ended.
A script that threw is an outcome, not an error: it comes back with Success false. An error means the run's fate is unknown — the stream broke, the session died, or ctx expired before the script finished.
*ScriptFinished*ScriptFinished describing how the script endedStaleRefError
1 methodStaleRefError is returned when a call was given a reference whose element is gone: the document it was seen in was replaced by a navigation or a reload, or the element was removed from it. A reference is never re-interpreted, so the call fails instead of acting on whatever took the element's place. Look again (Page.Wait, Page.GetObservation) and go on with the new reference.
It wraps the call's own error (ClickError, FillError, CommandError, ...), which errors.As still finds and whose Code is "stale_ref".
| Ref? | *Locator | Ref is the reference that went stale: the call's target, or the container it was to be looked for in. |
| URL | string | URL is where the frame the element was seen in is now, or the page's URL when that frame is gone too. When it differs from the URL the element was found at, the frame navigated; when it is the same, the document was reloaded or the element removed. Empty if it could not be read. |
Unwrap
method on StaleRefErrorUnwrap()Unwrap returns the call's own error.
Functions
27 functionsPackage-level functions: renting, listing, connecting to and stopping sessions, and the locator constructors.
AnyFrame
functionAnyFrame() → *LocatorAnyFrame names every frame, one after the other: the main document, then each iframe. It is what makes a JS locator search all frames, which it does not do by itself. Put in a frame container with In, it means that frame and the frames below it.
_, _ = page.Wait(ctx, browserscale.JS(
`[...document.querySelectorAll('button')].find(b => b.innerText === 'Accept all')`,
).In(browserscale.AnyFrame()))*Locator*Locator usable only as a containerAt
functionAt(x float64, y float64) → *LocatorAt targets viewport coordinates instead of an element.
Useful for clicking inside a canvas, hovering decorative regions, or dispatching events at synthetic positions. Action-only — using it in Page.Wait returns an error at send time. Note that only Click and MoveTo accept At; Scroll, Drag, Fill and Select all require a real element.
| x | float64 | viewport-relative x in CSS pixels |
| y | float64 | viewport-relative y in CSS pixels |
// Click at canvas-relative coordinates.
_, _ = page.Click(ctx, browserscale.At(120, 240))*Locator*Locator usable only as an action targetCaptcha
functionCaptcha() → *CaptchaConditionCaptcha matches as soon as a supported captcha or bot-protection challenge is on the page and waits for an answer. A widget that passed, or passes without interaction, does not count.
It is a state, like CSS: a challenge that is already showing matches at once. On a match the result's Kind is WaitKindCaptcha and its Captcha names the kind of challenge and the frame it sits in; hand the page to Page.SolveCaptcha to solve it.
Most challenges live in an iframe, so the condition looks at the whole page, every frame included. That is its own scope: the other conditions of the same wait keep theirs. Use CaptchaCondition.In to confine it.
res, err := page.Wait(ctx,
browserscale.CSS("#inbox"),
browserscale.Captcha(),
)
if err == nil && res.Kind == browserscale.WaitKindCaptcha {
_, err = page.SolveCaptcha(ctx, 0, 2)
}*CaptchaCondition*CaptchaCondition usable only as a Page.Wait conditionConnectSession
functionConnectSession(grpcUrl string, apiKey string, sessionId string) → *CloudBrowserConnectSession attaches to an already-running session via gRPC.
Use this when you have a session id and gRPC URL from a previous RentBrowser (for example stored across process restarts). Unlike RentBrowser this does not call the rent API — the session must already exist server-side.
| grpcUrl | string | the session's gRPC endpoint as returned by CloudBrowser.GrpcUrl |
| apiKey | string | API key authorizing access to the session |
| sessionId | string | id of the existing session to attach to |
browser, err := browserscale.ConnectSession(ctx, grpcUrl, apiKey, sessionId)
if err != nil {
log.Fatal(err)
}
defer browser.Close()*CloudBrowser*CloudBrowser attached to the existing session; the returnedCSS
functionCSS(selector string) → *LocatorCSS waits for / targets an element matching the given CSS selector.
Without Locator.In the selector is looked for on the whole page: the main document first, then every frame in the order they appear, frames nobody can see last. The result says which frame it was found in, so a button inside a consent or payment iframe needs no frame named. Use In to confine the search to one frame, one dialog or one component.
Where the element has to be visible (a wait condition or reaction, and every action), the selector means its first rendered match: matches that are not rendered at all (display:none, visibility:hidden, no size) are passed over, so a hidden copy such as the one in a closed mobile menu does not shadow the visible element. A covered or offscreen match is still rendered and stays the target. When a later match was taken, the result says which one in SelectorMatch. With Visible(false) a wait or reaction takes the first match.
When used in Page.Wait, the condition requires the element to be visible and to hold still for 500ms before it matches — the API's defaults for a condition that does not set them. Override per call with Locator.Visible / Locator.Steady (use .Steady(0) to disable the steady check).
When used as an action target (Click, etc.) the visible/steady fields are ignored — there are no corresponding fields on the action requests.
| selector | string | CSS selector matching the element |
// As a wait condition.
_, _ = page.Wait(ctx, browserscale.CSS("button.submit"))
// As an action target. Found wherever it is, also inside an iframe.
res, _ := page.Click(ctx, browserscale.CSS("button.accept"))
fmt.Println(res.Frame.Main, res.Frame.URL)*Locator*Locator usable as a wait condition, an action target or a containerFrame
functionFrame(container *Locator) → *LocatorFrame requires the element a locator names to be an iframe.
A container made with CSS, JS or a reference is entered as a frame when the element is an iframe and searched as a subtree when it is anything else, which is usually what is wanted. Wrap it in Frame to hear about it when the page gave something else: the call then fails with code "container_not_found", saying the element is not a frame, instead of quietly searching a subtree.
| container | *Locator | a CSS, JS or reference locator |
pay := browserscale.Frame(browserscale.CSS("iframe.pay"))
_, _ = page.Fill(ctx, browserscale.CSS("input[name=cardnumber]").In(pay), card)*Locator*Locator usable as a containerFrameByID
functionFrameByID(frameID string) → *LocatorFrameByID names one frame by its id, as a result's Frame.ID or Page.Frames report it. The id stays the same across navigations of the frame, but belongs to this session: prefer FrameURL, FrameName or the iframe's own selector in anything that is written down.
| frameID | string | the frame's id |
res, _ := page.Wait(ctx, browserscale.CSS("#card"))
frame := browserscale.FrameByID(res.Element.Frame.ID)
_, _ = page.EvaluateIn(ctx, frame, "document.title")*Locator*Locator usable only as a containerFrameName
functionFrameName(name string) → *LocatorFrameName names a frame by its name: window.name, which starts out as the iframe's name attribute. Otherwise as FrameURL.
| name | string | the frame's name |
_, _ = page.Fill(ctx, browserscale.CSS("input[name=q]").In(browserscale.FrameName("search")), "shoes")*Locator*Locator usable only as a containerFrameURL
functionFrameURL(pattern string) → *LocatorFrameURL names a frame by the URL of the document it shows.
It is a container: pass it to Locator.In, Page.EvaluateIn or ObservationOpts.Scope. The frame is looked for at any depth below the page, or below the container it is itself put in with In, and a frame a person can see is preferred over one that is hidden or has no size. Use this when the iframe element has nothing stable to select it by.
| pattern | string | URL wildcard; * matches any character span |
challenge := browserscale.FrameURL("*hcaptcha.com/*frame=checkbox*")
_, _ = page.Click(ctx, browserscale.CSS("#checkbox").In(challenge))// A frame inside a frame.
outer := browserscale.FrameURL("*/_Incapsula_Resource*")
inner := browserscale.FrameURL("*hcaptcha.com/*frame=checkbox*").In(outer)
_, _ = page.Click(ctx, browserscale.CSS("#checkbox").In(inner))*Locator*Locator usable only as a containerJS
functionJS(expression string) → *LocatorJS waits for / targets the result of a JavaScript expression.
Without Locator.In the expression runs in the page's main document, and only there. With In it runs in the document the container leads to; when the container is an element rather than a frame, the expression gets that element as __wrc.scope and has to return an element inside it.
Same wait defaults as CSS (visible, 500ms steady); these only apply when the expression returns a DOM Element. For non-Element truthy values (boolean, string, number, plain object) both are no-ops and the condition matches as soon as the value is truthy.
Use Locator.Visible(false) / Locator.Steady(0) on the returned Locator to opt out.
| expression | string | JavaScript expression |
_, _ = page.Wait(ctx, browserscale.JS("window.__ready === true"))// By text, inside one frame.
pay := browserscale.FrameURL("*checkout.example.com/*")
_, _ = page.Click(ctx, browserscale.JS(
`[...document.querySelectorAll('button')].find(b => /Pay/.test(b.innerText))`).In(pay))*Locator*Locator usable as a wait condition, an action target or a containerListBrowsers
functionListBrowsers(apiKey string) → []BrowserInfoListBrowsers reports the sessions an API key currently holds.
Use it to recover session ids the process lost — after a restart, or from a different machine entirely. Without it a rental is only reachable through the handle that created it, so a crash between rent and stop leaves a paid session running with nothing able to name it.
Only live sessions are listed; a stopped one is gone, not reported as ended.
| apiKey | string | API key whose sessions to list |
browsers, err := browserscale.ListBrowsers(ctx, apiKey)
if err != nil {
log.Fatal(err)
}
for _, b := range browsers {
fmt.Println(b.SessionId, b.CountryCode)
}[]BrowserInfo[]BrowserInfo oldest first, empty when the key holds noneMainFrame
functionMainFrame() → *LocatorMainFrame names the page's main document. A CSS locator put in it is not looked for in any iframe.
// Only the page's own button, not one in an embedded widget.
_, _ = page.Click(ctx, browserscale.CSS("button.accept").In(browserscale.MainFrame()))*Locator*Locator usable only as a containerNewBrowserConfig
functionNewBrowserConfig(apiKey string, rentDuration int, proxyHost string, proxyPort int, proxyUsername string, proxyPassword string) → *BrowserConfigNewBrowserConfig returns a BrowserConfig populated with the required rental fields. Optional fields are configured via the chainable With… setters before passing the config to RentBrowser.
| apiKey | string | API key authenticating the rental |
| rentDuration | int | lifetime of the session in seconds |
| proxyHost | string | upstream proxy host (empty string disables the proxy) |
| proxyPort | int | upstream proxy port (ignored when proxyHost is empty) |
| proxyUsername | string | proxy auth user (empty for unauthenticated proxies) |
| proxyPassword | string | proxy auth password (empty for unauthenticated proxies) |
cfg := browserscale.NewBrowserConfig("sk_…", 600, "", 0, "", "").
WithCountryCode("DE").
WithTimezone("Europe/Berlin")*BrowserConfig*BrowserConfig ready to be customized further or passed to RentBrowserProxyWithMasque
functionProxyWithMasque(hostPort string) → ProxyOptionProxyWithMasque carries HTTP/3 through a MASQUE proxy ("host:port") with the proxy's credentials, as BrowserConfig.WithMasque does for a rental.
| hostPort | string |
ProxyWithScheme
functionProxyWithScheme(scheme ProxyScheme) → ProxyOptionProxyWithScheme sets the proxy's protocol, as BrowserConfig.WithProxyScheme does for a rental.
| scheme | ProxyScheme |
Ptr
functionPtr(v T) → *TPtr returns a pointer to v. It is a convenience for the SDK's optional pointer fields where a zero value is meaningful and must be distinguished from "unset" — e.g. FillOpts.TimeoutMs: browserscale.Ptr(0.0) makes Fill one-shot, whereas a nil field takes the server default.
| v | T |
*TRef
functionRef(value string) → *LocatorRef targets the very element an earlier call found, by its reference.
Every result that names an element carries its reference as a ready Locator (WaitElement.Ref, ElementResult.Ref, OccluderInfo.Ref, ...), so this constructor is only needed for a reference that arrived as text: an observation prints one per frame ("# ref @<document>"), and a row's number followed by that suffix is the element's reference.
A reference names its element and the document it lives in, so no frame is named with it and Locator.In does not apply. It stays good while the element is in its document. Once a navigation replaced the document, or the element was removed, a call given it fails with a *StaleRefError instead of acting on whatever took its place.
| value | string | the reference, as Locator.RefString returns it |
res, _ := page.Wait(ctx, browserscale.CSS(".result"))
_, err := page.Click(ctx, res.Element.Ref)// From an observation: row 47 of the frame whose header says "# ref @9F2C...".
_, err := page.Click(ctx, browserscale.Ref("47@9F2C41D0A1B24C7E8F3A5D6B7C8E9F01"))*Locator*Locator usable as an action target or a containerRentBrowser
functionRentBrowser(config *BrowserConfig) → *CloudBrowserRentBrowser rents a new browser session and returns a connected handle.
Calls the browserscale rent endpoint with the supplied BrowserConfig, opens a gRPC connection to the assigned session host, and returns a ready-to-use CloudBrowser. On any failure the partially-rented session is best-effort released.
| config | *BrowserConfig | rental parameters built with NewBrowserConfig |
cfg := browserscale.NewBrowserConfig("sk_…", 600, "", 0, "", "")
browser, err := browserscale.RentBrowser(ctx, cfg)
if err != nil {
log.Fatal(err)
}
defer browser.Close()*CloudBrowser*CloudBrowser ready to drive the rented session; callRequest
functionRequest(urlPattern string) → *RequestConditionRequest matches the first request whose URL matches urlPattern.
Unlike CSS or Captcha, a request is an event, not a state: only a request issued after the wait started counts. Start the wait before the action that triggers the request — in a goroutine, or race it in the same call. It watches the whole browser session: the page, its frames, and any tab or popup it opens, across navigations.
On a match the result's Kind is WaitKindRequest and Request carries the method, URL, headers and body.
| urlPattern | string | URL wildcard; * matches any character span |
res, err := page.Wait(ctx,
browserscale.Request("https://example.com/api/submit*"),
browserscale.Timeout(10000),
)
if err == nil {
fmt.Println(res.Request.Method, res.Request.Body)
}*RequestCondition*RequestCondition usable only as a Page.Wait conditionResponse
functionResponse(urlPattern string) → *ResponseConditionResponse matches the response to the first request whose URL matches urlPattern, once it has fully arrived.
Same event semantics and scope as Request: only a request issued after the wait started counts, so start the wait before the action. On a match the result's Kind is WaitKindResponse and Response carries the status, headers and body.
| urlPattern | string | URL wildcard, matched against the request URL |
res, err := page.Wait(ctx,
browserscale.Response("https://example.com/api/token*"),
)
if err == nil {
fmt.Println(res.Response.StatusCode, res.Response.Body)
}*ResponseCondition*ResponseCondition usable only as a Page.Wait conditionSetApiEndpoint
functionSetApiEndpoint(endpoint string)SetApiEndpoint overrides the HTTP rent/stop endpoint.
Defaults to https://api.browserscale.cloud. Call this before any RentBrowser/StopBrowser call if you need to point at a private browserscale deployment.
| endpoint | string | base URL of the rent/stop service, with no trailing slash |
browserscale.SetApiEndpoint("https://browserscale.internal.example.com")StopAllBrowsers
functionStopAllBrowsers(apiKey string) → intStopAllBrowsers releases every session an API key holds.
The blunt instrument, for cleaning up after a run that leaked sessions — a crashed worker pool, an interrupted test. It ends sessions this process never created, including ones another machine is using, so it is not a way to tidy up "my" sessions in a shared account.
Each session's billing stops with it, as with StopBrowser.
| apiKey | string | API key whose sessions to release |
stopped, err := browserscale.StopAllBrowsers(ctx, apiKey)intint how many sessions were stoppedStopBrowser
functionStopBrowser(apiKey string, sessionId string) → *SessionUsageStopBrowser releases a session without needing a CloudBrowser handle.
Useful when a session id was persisted across processes and the rental outlived the original handle. Only calls the rent stop endpoint; there is no gRPC connection to close in this form.
| apiKey | string | API key the session was rented with |
| sessionId | string | id of the session to release |
usage, err := browserscale.StopBrowser(context.Background(), apiKey, sessionId)*SessionUsage*SessionUsage what the session consumed over its whole life; nilTimeout
functionTimeout(ms float64) → WaitArgTimeout overrides the Page.Wait timeout.
When omitted, the API's default of 30s applies. Pass once per Wait call as one of the variadic arguments.
| ms | float64 | timeout in milliseconds |
_, _ = page.Wait(ctx, browserscale.CSS("#done"), browserscale.Timeout(5000))WaitArga WaitArg suitable for passing to WaitWithCookies
functionWithCookies() → IdentityOptionWithCookies also returns the session's cookies in ClientIdentity.Cookies.
WithStorage
functionWithStorage() → IdentityOptionWithStorage also returns the session's localStorage in ClientIdentity.Storage.
WithStorageOrigin
functionWithStorageOrigin(origin string) → IdentityOptionWithStorageOrigin restricts WithStorage to a single origin (and enables it), e.g. "https://example.com".
| origin | string |
Errors
10 errorsReturned as the error of the command they belong to, each with a stable code and typed detail. Recover them with errors.As.
ClickError
structClickError is returned as the error from Page.Click / Page.ClickWith when the click did not land (the element was occluded and the point could not be reached). It implements the error interface, so the ordinary res, err := page.Click(...) shape keeps working; recover the structured detail with errors.As:
res, err := page.Click(ctx, browserscale.CSS("#buy")) var ce *browserscale.ClickError if errors.As(err, &ce) { // ce.Code, ce.Message, ce.Occluder describe the blocker }
| Code | string | Code is a machine-stable failure code, e.g. "occluded_no_reachable_point" (target fully covered, no exposed part reachable), "occluded_after_evade" (a reposition was tried but the target was still covered) or "captcha_failed" (a captcha held the click and could not be solved, see CloudBrowser.EnableCaptchaAutoSolve). Where the target was looked for has its own codes: "container_not_found" (a container given with Locator.In is not on the page), "outside_scope" (a JS target returned an element outside its container) and "stale_ref" (a reference whose element is gone; the call returns a StaleRefError around this error). |
| Message | string | Message is a human-readable description. |
| Occluder? | *OccluderInfo | Occluder is the intercepting element (present for occlusion codes). |
| EvadeAttempted | bool | EvadeAttempted reports whether a pointer reposition was tried before giving up. |
| FocusedPageId | string | FocusedPageId is, for Code "page_not_focused", the page that has the focus. The call returns a PageNotFocusedError around this error then. |
CommandError
structCommandError is the failure detail of a command the browser carried out but the page would not go along with. It is the error type for the commands that have nothing to report beyond what went wrong; the richer failures have their own type (ClickError, FillError, DragError) carrying the same Code/Message pair plus their own detail.
It implements the error interface, so the ordinary res, err := ... shape keeps working and res stays readable alongside it. Recover the code with errors.As:
res, err := page.Evaluate(ctx, "document.title.toUpperCase()") var ce *browserscale.CommandError if errors.As(err, &ce) && ce.Code == "threw" { // the expression itself is broken; ce.Message has the exception text }
A CommandError never reports an outage. A dead session, a closed page or a malformed call arrive as a plain transport error instead, so errors.As matching here tells you the fault is in the page or in what you asked of it — which is the difference between retrying and fixing your code.
| Command | string | Command is the call that failed, e.g. "evaluate". |
| Code | string | Code is machine-stable and lowercase, and is scoped to Command: the same string can mean different things for different commands, so branch on it together with the call you made. |
| Message | string | Message is human-readable detail and may be empty. Never parse it; Code is the contract and this text is free to change. |
DragError
structDragError is returned as the error from CloudBrowser.Drag variants when the source element could not be acquired/pressed. Drag picks up the source with the same smart click as Page.Click, so a pre-drag failure is a click failure: Code/Message mirror it and the full click diagnostics live under ClickError. Implements the error interface; recover with errors.As.
| Code | string | Code is mirrored from the underlying click failure: "not_found", "occluded_no_reachable_point" or "occluded_after_evade". Or "captcha_failed": a captcha held the drag and could not be solved (see CloudBrowser.EnableCaptchaAutoSolve). |
| Message | string | Message is a human-readable description (mirrors ClickError.Message). |
| ClickError? | *ClickError | ClickError is the underlying click-core failure at the source pickup. |
FillError
structFillError is returned as the error from Page.Fill / Page.FillWith when the field could not be focused/typed. Fill focuses the field with the exact same smart click as Page.Click, so a pre-typing failure is a click failure: Code/Message mirror it and the full click diagnostics live under ClickError. It implements the error interface, so the ordinary res, err := page.Fill(...) shape keeps working; recover the detail with errors.As:
res, err := page.Fill(ctx, browserscale.CSS("#email"), "a@b.com") var fe *browserscale.FillError if errors.As(err, &fe) && fe.ClickError != nil { // fe.ClickError.Occluder describes the blocker }
| Code | string | Code is the machine-stable failure code. Click-phase codes ("not_found", "occluded_no_reachable_point", "occluded_after_evade") mirror the underlying focus click, with diagnostics under ClickError. The focus codes are "focus_stolen" (another element took focus — FocusedElement names it; Fill is strictly target-bound and will not type into the thief) and "focus_lost" (focus left the target and nothing is focused). For untargeted stream typing that lets focus move (e.g. OTP), use Type. "captcha_failed": a captcha held the fill and could not be solved (see CloudBrowser.EnableCaptchaAutoSolve). |
| Message | string | Message is a human-readable description (mirrors ClickError.Message). |
| ClickError? | *ClickError | ClickError is the underlying click-core failure (locate or occlusion) that prevented focusing/typing. Present for the click-phase codes; absent for "focus_stolen"/"focus_lost". |
| FocusedBackendNodeId | int32 | FocusedBackendNodeId is the node that held focus when Fill gave up (0 if nothing was focused), for the "focus_stolen"/"focus_lost" codes. |
| FocusedElement? | *FocusedElement | FocusedElement describes the element that grabbed focus instead of the target ("focus_stolen"), so you can act on it (e.g. a consent button). |
| TargetEditable? | *bool | TargetEditable and TargetValueLength report the fill target's own state at the point of failure (the focus codes): whether it is still an editable text sink and its current text length. Both nil when not reported. |
| TargetValueLength? | *int |
MoveError
structMoveError is returned as the error from Page.MoveTo when the target could not be located. A move has no occlusion notion, so this is the only semantic failure. Implements the error interface; recover with errors.As.
| Code | string | Code is "not_found" or "page_not_focused", or one of the codes about where the target was looked for: "container_not_found", "outside_scope", "stale_ref". |
| Message | string | Message is a human-readable description. |
| FocusedPageId | string | FocusedPageId is, for Code "page_not_focused", the page that has the focus. The call returns a PageNotFocusedError around this error then. |
PageClosedError
structPageClosedError is returned by a Page call when the page has closed. FocusedPage is the page that has the focus now, usually the one that opened the closed page.
| PageId | string | PageId is the id of the page that closed. |
| FocusedPage? | *Page | FocusedPage is the page that has the focus now. |
var closed *browserscale.PageClosedError
if errors.As(err, &closed) {
page = closed.FocusedPage
}ScrollError
structScrollError is returned as the error from Page.ScrollTo when the target could not be located/scrolled. Implements the error interface; recover with errors.As.
| Code | string | Code is "not_found", or one of the codes about where the target was looked for: "container_not_found", "outside_scope", "stale_ref". |
| Message | string | Message is a human-readable description. |
SelectOptionError
structSelectOptionError is returned as the error from CloudBrowser SelectByXxx calls when the option could not be selected. selectOption is programmatic (no pointer gate), so it only reports semantic failures. Implements the error interface; recover with errors.As.
| Code | string | Code is "not_found" (the <select> was not located) or "option_not_found" (no option matched the requested index/value/text), or one of the codes about where the <select> was looked for: "container_not_found", "outside_scope", "stale_ref". |
| Message | string | Message is a human-readable description. |
SolveCaptchaError
structSolveCaptchaError is returned as the error from Page.SolveCaptcha when the challenge was not solved. Implements the error interface; recover with errors.As.
| Code | string | Code is "not_found", "unsupported", "solve_failed", "blocked", "timeout", "page_closed" or "cancelled"; see Page.SolveCaptcha. |
| Message | string | Message is a human-readable description. |
| Kind | string | Kind is the type of challenge found, a short stable name such as "turnstile"; empty when none was. |
| SolveId | string | SolveId is the solve's id in the ContextEventCaptchaDetected and ContextEventCaptchaResolved events; empty when no solve ran. |
WaitError
structWaitError is returned as the error from Page.Wait when no condition matched before the deadline. It implements the error interface, so the ordinary res, err := page.Wait(...) shape keeps working; recover the structured detail (including the per-condition breakdown) with errors.As:
res, err := page.Wait(ctx, browserscale.CSS(".ready")) var we *browserscale.WaitError if errors.As(err, &we) { for _, c := range we.Conditions { log.Printf("condition %d: %s", c.Index, c.State) } }
| Code | string | Code is a machine-stable failure code, currently always "timeout". |
| Message | string | Message is a human-readable description. |
| Conditions | []WaitConditionStatus | Conditions holds the per-condition status, same order/length as the conditions passed to Wait. |
Options
11 typesOptional settings a command accepts.
CaptchaAutoSolveOpts
structCaptchaAutoSolveOpts configures CloudBrowser.EnableCaptchaAutoSolve. Zero values use the server defaults.
| SolveTimeoutMs | int32 | SolveTimeoutMs is the budget for one solve, in milliseconds. 0 = 60000. |
| RetryAmount | int32 | RetryAmount is the per-solve retry cap, as in Page.SolveCaptcha. 0 = the solver's own default. |
| OnFailure | string | OnFailure is what an action held by a solve does when the solve fails. "" or "fail" = it ends with code "captcha_failed" (default). "continue" = it carries on as if the solve had succeeded. |
| Unfocused | string | Unfocused is what happens to a captcha on a page that does not have the focus. Input only reaches the focused page, so it cannot be solved there as it is. "" or "wait" = it is reported (State "waiting_for_focus") and solved once the page has the focus (default). "focus" = the page is brought to the front and it is solved right away. |
| MaxSolvesPerMinute | int32 | MaxSolvesPerMinute caps the solves that start per page within any 60 seconds. Further captchas are reported as "skipped" and resolved with code "limit_reached". Protects against a page that keeps putting one up. 0 = 5. |
ClickOpts
structClickOpts customizes a Page.ClickWith call. Zero/empty values mean "use the server default".
| Button | string | Button is the mouse button to use. Valid: "left" (default), "right", "middle". |
| ClickCount | int32 | ClickCount controls single/double-click. 0 or 1 = single click (default), 2 = double-click. |
| Action | string | Action selects the mouse phase. "" or "click" = full mouseDown+mouseUp (default). "press" only dispatches mouseDown. "release" only dispatches mouseUp at the current cursor position. |
CookieParam
structCookieParam is one cookie returned by GetCookies / passed to SetCookies. Name, Value, Domain, and Path are the common required identity fields; optional attributes mirror the browser's CookieParam shape: URL, Secure, HTTPOnly, SameSite, Expires, Priority, SourceScheme, SourcePort, and PartitionKey.
| Name | string | |
| Value | string | |
| URL? | *string | |
| Domain | string | |
| Path | string | |
| Secure? | *bool | |
| HTTPOnly? | *bool | |
| SameSite? | *string | |
| Expires? | *float64 | |
| Priority? | *string | |
| SourceScheme? | *string | |
| SourcePort? | *int | |
| PartitionKey? | *CookiePartitionKey |
DomMirrorOptions
structDomMirrorOptions configures Page.MirrorDom and Page.StartDomMirror.
| Depth | int32 | Depth is how many levels to serialize up front. 0 uses the server default of 2 — #document → <html> → <head>/<body>, enough to draw a collapsed tree. -1 walks everything and gives up what the mirror is for. |
| Pierce | bool | Pierce descends into author shadow roots. Fixed for the life of the mirror. |
EvaluateOpts
structEvaluateOpts customizes a Page.EvaluateWith call. Zero/empty values mean "use the default".
| In? | *Locator | In is where the expression runs, as the container of Page.EvaluateIn: a frame, or an element the expression then sees as __wrc.scope. nil is the main document. |
| TimeoutMs | float64 | TimeoutMs is how long a promise the expression answers with is waited for, in milliseconds. 0 = 30000. After that the call fails with "timeout" and the promise goes on in the page. |
| NoAwait | bool | NoAwait starts a promise without waiting for it: the call returns at once, with no value. For work that goes on while the script does something else; keep the promise in a variable of the page to come back to it. |
FillOpts
structFillOpts customizes a Page.FillWith call. Zero/empty values mean "use the server default".
| ClearFirst | bool | ClearFirst, when true, wipes the field's existing content with Ctrl+A, Delete before typing. Default (false) appends to whatever is already there. |
| TimeoutMs? | *float64 | TimeoutMs bounds focus acquisition (locate, scroll, settle, un-occlude) in ms, mirroring the click timeout. nil = server default (5000). It is a pointer because 0 is meaningful: browserscale.Ptr(0.0) makes Fill one-shot (no retry). |
| SteadyMs? | *float64 | SteadyMs is the settle window in ms before the focus click, mirroring the click steady-time. nil = server default (750); browserscale.Ptr(0.0) skips settling. |
NetworkCaptureOptions
structNetworkCaptureOptions configures CloudBrowser.CaptureNetwork.
There is deliberately no byte-cap option: kept bodies are stored on a machine shared with other sessions, so the server owns the quota. When a session's bodies exceed it, the oldest are dropped first.
| Patterns | []string | Patterns are URL wildcards to capture; nil captures every request the session makes. Prefix a pattern with "!" to exclude it, which is the short way to say "everything except this". |
| Bodies | NetworkBodies | Bodies selects response-body capture. Empty means NetworkBodiesNone. Request bodies are kept whenever a request has one. |
| BodyPatterns | []string | BodyPatterns narrows body capture to a subset of the captured requests; nil applies Bodies to all of them. Use it to log every request but only keep the payloads you care about. |
ObservationOpts
structObservationOpts customizes a Page.GetObservationWith call. Zero/empty values mean "use the server default".
| Format | string | Format is "text" (default) for the compact line format meant to be handed to a model as-is, or "json" for the structured form. Only the requested representation is built, so asking for one does not cost the other. |
| MaxElementsPerFrame | int32 | MaxElementsPerFrame caps emitted elements per frame. 0 = server default (800). This is a safety net against runaway documents; MaxTotalTokens is the limit that normally binds. |
| MaxTextLength | int32 | MaxTextLength caps human-readable strings (labels, text, values) in characters. 0 = server default (300). Identifier-like attributes (type, name, role) have their own fixed, shorter cap and are unaffected. |
| MaxTotalTokens | int32 | MaxTotalTokens budgets the whole page in estimated tokens rather than characters, because the same character count is worth roughly four times as many tokens in CJK text as in ASCII. 0 = server default (8000). Frames are visited in tree order and each gets whatever is left. A reserve on top of the budget, a quarter of it and at most 2000 tokens, is kept for child frames, so a long main document does not push out the consent or payment frame further down. The budget is where a frame starts leaving things out, not the size of the result: from a "# budget spent" line on, the frame lists only what can be acted on, with its headings. A result can therefore come to about twice this value. |
| IncludeBounds | bool | IncludeBounds adds bounds="x,y,w,h" to every row. Off by default; bounds cost about as much as the rest of a row and are rarely needed, since elements are addressed by their reference. |
| ViewportOnly | bool | ViewportOnly limits the walk to elements intersecting the frame's current viewport. Off by default. |
| Scope? | *Locator | Scope observes only part of the page, so a follow-up look at a form costs the form and not the ads around it. Nil is the whole page. An element locator (CSS, JS or a reference) scopes to that element's subtree; like any locator it can be confined with Locator.In. A frame (FrameURL, FrameName, FrameByID, MainFrame) scopes to that frame's document. Child iframes reached inside the scope are still visited. |
ReactionOpts
structReactionOpts customizes Page.AddReactionWith and CloudBrowser.AddReactionWith. Zero/empty values mean "use the server default".
| On? | *Locator | On overrides the click target. Nil = click the matched element itself. Provide a CSS or JS Locator to click a different element, resolved in the matched element's frame (e.g. a modal's close "X"). It takes no container of its own; a reference or At locator is rejected. |
| Button | string | Button is the mouse button for the click. Valid: "left" (default), "right", "middle". |
| ClickCount | int32 | ClickCount controls single/double-click. 0 or 1 = single click (default), 2 = double-click. |
| IntervalMs | float64 | IntervalMs is the poll cadence in milliseconds for the shared page loop. 0 = server default (300ms). |
ReadCanvasOpts
structReadCanvasOpts customizes a Page.ReadCanvasWith call. Zero/empty values mean "use the server default".
| Format | string | Format is the output encoding. "" or "png" (default), "jpeg", "webp", or "rgba" for the raw unpremultiplied RGBA pixel buffer. |
| Quality | int32 | Quality is the encode quality 0-100 for "jpeg"/"webp" (ignored otherwise). 0 = server default (90). |
| SX | int32 | SX, SY, SW, SH is an optional sub-rectangle in canvas pixels (mirrors getImageData(sx, sy, sw, sh)). The full canvas is read when SW/SH <= 0. |
| SY | int32 | SX, SY, SW, SH is an optional sub-rectangle in canvas pixels (mirrors getImageData(sx, sy, sw, sh)). The full canvas is read when SW/SH <= 0. |
| SW | int32 | SX, SY, SW, SH is an optional sub-rectangle in canvas pixels (mirrors getImageData(sx, sy, sw, sh)). The full canvas is read when SW/SH <= 0. |
| SH | int32 | SX, SY, SW, SH is an optional sub-rectangle in canvas pixels (mirrors getImageData(sx, sy, sw, sh)). The full canvas is read when SW/SH <= 0. |
SelectOpts
structSelectOpts customizes a SelectByXxxWith call. Zero/empty values mean "use the server default".
| NoEvents | bool | NoEvents picks the option silently without firing input/change events. Default (false) fires the standard events. |
Results
17 typesWhat commands hand back.
DragResult
structDragResult is the outcome of a CloudBrowser.Drag gesture: the resolved source element and the start/end coordinates of the performed drag.
| Success | bool | |
| Ref? | *Locator | Ref names the dragged element, and Frame the frame it was found in; as in ElementResult. |
| Frame | FrameRef | |
| StartX | float64 | |
| StartY | float64 | |
| EndX | float64 | |
| EndY | float64 | |
| Captchas | []CaptchaInterruption | Captchas lists the captcha solves that held the drag, in order. Nil if none did. |
| SelectorMatch? | *SelectorMatch | SelectorMatch is set when a CSS source resolved to other than the selector's first match. |
ElementResult
structElementResult is the outcome of an element interaction such as Page.Click, Page.Fill or Page.ScrollTo: the resolved element plus the root-relative coordinates the action was performed at.
| Success | bool | |
| Ref? | *Locator | Ref names the element the call acted on: pass it to a later action to act on exactly this element again, or to Locator.In to look inside it. Nil for a call that was given coordinates (At). See Ref for how long it stays good. |
| Frame | FrameRef | Frame is the frame the element was found in. A CSS target is looked for on the whole page, so this is where to read which frame it was. |
| IsVisible | bool | |
| Bounds | Rect | |
| RootX | float64 | |
| RootY | float64 | |
| Captchas | []CaptchaInterruption | Captchas lists the captcha solves that held a Page.Click or Page.Fill while it ran, in order (see CloudBrowser.EnableCaptchaAutoSolve). Nil if none did, and always nil for the other actions. |
| SelectorMatch? | *SelectorMatch | SelectorMatch is set when a CSS target resolved to other than the selector's first match. |
EvaluateResult
structEvaluateResult carries the outcome of a JS evaluate call.
If the expression returned a DOM element, Ref/IsVisible/Bounds are populated and Value is nil. Otherwise Value holds the parsed JSON value (string/number/bool/[]any/mapstringany/nil). On parse failure Value falls back to the raw server string so the caller is never empty- handed.
| Success | bool | Success is false only when the expression never produced a value, in which case the error carries the reason. An expression that answers falsy is a successful evaluation, so this does not mean "the answer was false". |
| Value | any | |
| Ref? | *Locator | Ref names the element the expression returned, ready to pass to an action or to Locator.In; nil when it returned anything else. |
| Frame | FrameRef | Frame is the frame the expression ran in. |
| IsVisible | bool | |
| Bounds | Rect |
InspectResult
structInspectResult describes the topmost element hit at viewport-relative (x, y). A nil Ref (and BackendNodeId == 0) means nothing was found at that position.
| Ref? | *Locator | Ref names the element, ready to pass to an action or to Locator.In, and Frame is the frame it lives in. |
| Frame | FrameRef | |
| BackendNodeId | int32 | BackendNodeId and FrameId are the same element as the DOM mirror addresses it (DomMirror.Node, DomMirror.Reveal, Page.HighlightNode). |
| FrameId | string | |
| TagName | string | |
| TextContent | string | |
| IsVisible | bool | |
| Bounds | Rect |
InterceptedResponse
structInterceptedResponse describes a network response captured by a Response wait condition or CloudBrowser.WaitForAnyResponse.
| Url | string | |
| StatusCode | int32 | |
| Headers | []Header | |
| Body | string |
OccluderInfo
structOccluderInfo describes the element that intercepted a click — the element sitting on top of the target at the intended click point. Coordinates are in root-viewport CSS pixels. Populated on ClickError for occlusion failures so the caller can locate and clear the blocker (e.g. find its close button).
| Ref? | *Locator | Ref names the blocker itself: pass it to Page.Click to click it, or to Locator.In to look for its close button inside it. Nil when it could not be named. |
| FrameId | string | FrameId is the frame the blocker lives in, which may differ from the target's (a page-level modal covering an iframe). |
| TagName | string | |
| Id | string | |
| ClassName | string | |
| Text | string | |
| Bounds | Rect | |
| PointerEvents | string | PointerEvents is the blocker's computed pointer-events keyword (e.g. "auto", "none", "all"). Lets you tell an invisible pass-through layer from one that genuinely swallows the click. |
| Visibility | string | Visibility is the blocker's computed visibility keyword ("visible", "hidden", "collapse"). |
| Opacity | float64 | Opacity is the blocker's computed opacity (0..1). 0 means visually invisible but it may still intercept clicks depending on PointerEvents. |
| ZIndex | string | ZIndex is the blocker's computed effective z-index as a string ("0" when auto / not stacked). |
| HittableWhileInvisible | bool | HittableWhileInvisible is true when the blocker intercepts clicks even while invisible (computed pointer-events in {all, painted, fill, stroke}): a real click is swallowed even at visibility:hidden / opacity:0. When false and the element is invisible, a real click would fall through. |
| Position | string | Position is the computed position keyword. "fixed"/"sticky" means the blocker is pinned (by itself or an ancestor) and stays put no matter where the pointer goes — clear it by scrolling the target out from under it; ordinary overlays often collapse once the pointer leaves. |
PageInfo
structPageInfo describes an open page (tab or popup) inside a browser context, as CloudBrowser.Pages found it.
| Page? | *Page | Page is the handle to act on the page. |
| BrowserContextId | string | |
| Url | string | |
| Title | string | |
| Viewport | Rect | |
| FrameTree | FrameInfo | |
| IsFocused | bool | IsFocused is whether this is the page that has the focus; exactly one page has it. See CloudBrowser.FocusedPage. |
| IsPopup | bool | IsPopup is whether the page is a popup window (window.open with window features) rather than a tab. |
| Opener? | *Page | Opener is the page that opened this one, if it is still open. Also set for rel=noopener, since the page still came from it. |
| OpenerFrameId | string | OpenerFrameId is the frame that opened this page, which may be a frame of Opener other than its main frame. |
ReactionInfo
structReactionInfo describes a still-pending reaction, as returned by Page.ListReactions and CloudBrowser.ListReactions. One-shot reactions that have already fired are gone and never appear here.
| ReactionID | string | ReactionID is the stable id assigned by AddReaction (pass to RemoveReaction). |
| MatchSelector | string | MatchSelector is set if the reaction matches by CSS selector. |
| MatchJsExpression | string | MatchJsExpression is set if the reaction matches by JS expression. |
| ActionSelector | string | ActionSelector is set if the click target differs from the matched element. |
| ActionJsExpression | string | ActionJsExpression is set if the click target differs from the matched element. |
| Match? | *Locator | Match is the locator the reaction watches for, as it was given to AddReaction: the selector or expression above together with the container it was put in with Locator.In, and its Visible setting. Print it with Locator.String to see where the reaction looks. |
| Visible | bool | Visible reports whether the match additionally requires visibility. |
| AllPages | bool | AllPages reports whether the reaction was registered for every page (CloudBrowser.AddReaction) rather than for one. |
ReadCanvasResult
structReadCanvasResult is the pixel readback of a <canvas>, returned by Page.ReadCanvas. DataBase64 holds the encoded image bytes (PNG by default) or the raw RGBA buffer when Opts.Format == "rgba". OriginClean reports whether the canvas was untainted (informational; the read succeeds either way).
ScreenshotResult
structScreenshotResult is a single captured image of the page, returned by Page.Screenshot. DataBase64 holds the encoded image bytes (PNG by default); Width and Height are in physical pixels.
| DataBase64 | string | |
| Width | int32 | |
| Height | int32 |
ScriptFinished
structScriptFinished says how a run ended.
| Success | bool | Success is false when the script failed to compile or threw; Result then holds the message. |
| Result | string | Result is the return value as JSON, or the error message. |
| Stopped | bool | Stopped is true when the run was cancelled, or the session went away under it, rather than the script returning on its own. |
ScriptResult
structScriptResult is the outcome of a blocking Page.RunScript.
| Success | bool | Success is false when the script failed to compile or threw; Result then holds the message. |
| Result | string | Result is the return value as JSON, or "undefined" when the script returned nothing. On failure it is the error message. |
| RunId | string | RunId names the run. It arrives with the reply, so it is only useful after the fact — to match up log lines a separate follower already saw. |
| Log | []ScriptLogEntry | Log is everything the script printed, in order. |
| Truncated | bool | Truncated is true when the script printed more than the reply holds, in which case Log is the tail of the output rather than all of it. |
ScriptRunInfo
structScriptRunInfo is one run still in flight, as Page.ListScriptRuns reports it.
| RunId | string | |
| Running | time.Duration | Running is how long the run has been going. |
SelectOptionResult
structSelectOptionResult reports which <option> a SelectByXxx call ended up selecting.
StreamAnswer
structStreamAnswer is the browser's reply to a CloudBrowser.StartStream.
| AnswerSDP | string | SDP answer to apply as your peer's remote description. |
| Viewport | Rect | Root viewport in CSS pixels, the coordinate space the stream's input data channels expect. X/Y are always 0. Map your on-screen pointer positions into this space before sending them; the video may be displayed at any size. It arrives with the answer rather than from a separate Pages call so it cannot race the stream, and the browser pushes {"type":"viewport","width":W,"height":H} on the reliable "input" channel whenever it changes, including when the stream moves to another page. |
WaitResult
structWaitResult is the outcome of a Page.Wait call: which condition matched (Index, in argument order), what kind it was, and what it matched.
Exactly one of Element, Captcha, Request and Response is set, according to Kind. On a timeout, Index is -1, Kind is empty and the error is a *WaitError.
| Index | int32 | |
| Kind | WaitKind | |
| Element? | *WaitElement | Element is the matched element, set iff Kind is WaitKindElement. |
| Captcha? | *WaitCaptcha | Captcha is the matched challenge, set iff Kind is WaitKindCaptcha. |
| Request? | *InterceptedRequest | Request is the matched request, set iff Kind is WaitKindRequest. |
| Response? | *InterceptedResponse | Response is the matched response, set iff Kind is WaitKindResponse. |
Data types
48 typesEverything else the API passes around: handles, events, records and enums.
AuthSession
structAuthSession is a portable snapshot of a context's signed-in Google account and/or DBSC sessions. All fields are optional so a context that only has DBSC (no primary account) or only a sign-in (no DBSC) round-trips.
Pair with CloudBrowser.GetCookies / CloudBrowser.SetCookies and CloudBrowser.GetStorage / CloudBrowser.SetStorage to fully move a persona between fresh contexts. Call CloudBrowser.SetAuthSession before navigating.
| GaiaID? | *string | |
| Email? | *string | |
| RefreshToken? | *string | |
| WrappedBindingKey? | *string | |
| SigninScopedDeviceID? | *string | |
| SyncConsent? | *bool | |
| DbscSessions | []DbscSession |
CaptchaEvent
structCaptchaEvent describes a captcha solve in a ContextEventCaptchaDetected or ContextEventCaptchaResolved event. SolveId and InterruptedCommand are set for both; the other fields for the one they name.
| SolveId | string | SolveId identifies the solve in both events and in the Captchas of the actions it held. |
| Kind | string | Kind (detected) is the type of challenge, a short stable name such as "turnstile". |
| InterruptedCommand | string | InterruptedCommand is the action running on the page when the captcha appeared ("click", "fill", "type", "drag"), held until the solve ended. Empty if none was. |
| FrameId | string | FrameId (detected) is the frame the challenge was found in. |
| Trigger | string | Trigger (detected) is "auto" (auto-solve) or "command" (Page.SolveCaptcha). |
| State | string | State (detected) is "solving" (the solve starts now), "waiting_for_focus" (the page does not have the focus and auto-solve waits for it, see CaptchaAutoSolveOpts.Unfocused) or "skipped" (the page reached CaptchaAutoSolveOpts.MaxSolvesPerMinute; the resolved event follows at once with code "limit_reached"). |
| Success | bool | Success (resolved) reports whether the challenge was solved. |
| DurationMs | float64 | DurationMs (resolved) is the time from detection to the end, in milliseconds, including any wait for the focus. |
| Attempts | int32 | Attempts (resolved) is how many interaction rounds the solve needed; 0 if it never got to interact. |
| InterruptedOutcome | string | InterruptedOutcome (resolved) is what InterruptedCommand does now; see CaptchaInterruption.Outcome. |
| Error? | *CommandError | Error (resolved) is set iff Success is false. Codes: "solve_failed", "blocked" (the challenge was answered and the site replied with a block; solving again in this session will not help), "timeout", "limit_reached", "page_closed", "disabled" (auto-solve was disabled before the solve started) and "cancelled" (a navigation of the page started during the solve). |
CaptchaInterruption
structCaptchaInterruption is a captcha solve that held an action while it ran. Listed under Captchas in the action's result.
| SolveId | string | SolveId is the solve's id, as in the ContextEventCaptchaDetected and ContextEventCaptchaResolved events. |
| Success | bool | Success reports whether the challenge was solved. |
| DurationMs | float64 | DurationMs is how long the action was held, in milliseconds. |
| Outcome | string | Outcome is what the action did after the solve: "resumed" (it carried on in the same document), "restarted" (the solve replaced the document, so it started over), "continued" (the solve failed and the action carried on anyway, see CaptchaAutoSolveOpts.OnFailure) or "failed" (the solve failed and the action ended with code "captcha_failed"). |
ClientIdentity
structClientIdentity is everything the browser reports about itself on the wire, so an out-of-browser HTTP client can reproduce matching request headers: the User-Agent, the full UA client-hint set, the Accept-Language, and the session's proxy. Cookies and Storage are populated only when requested via WithCookies / WithStorage.
| UserAgent | string | |
| AcceptLanguage | string | |
| Platform | string | |
| PlatformVersion | string | |
| Architecture | string | |
| Bitness | string | |
| Model | string | |
| Mobile | bool | |
| Wow64 | bool | |
| Brands | []UaBrand | |
| FullVersionList | []UaBrand | |
| Proxy | ProxyConfig | |
| Cookies | []CookieParam | Cookies is set when GetClientIdentity is called WithCookies(). |
| Storage | []StorageOriginEntry | Storage is set when GetClientIdentity is called WithStorage(). |
ContextEvent
structContextEvent is one change to the browser's pages, or a captcha solve or a reaction's click on one of them. Applying the page events in order to the last snapshot gives the pages as they are, without polling CloudBrowser.Pages. An event can restate what the snapshot before it already shows; each one sets state rather than changing it, so applying it again is harmless.
The captcha and reaction events are reports, not state: a listener that fell so far behind that it got a new snapshot may have missed some.
| Kind | ContextEventKind | |
| Pages | []*PageInfo | Pages is set for ContextEventSnapshot. |
| Opened? | *PageInfo | Opened is set for ContextEventPageOpened. |
| Page? | *Page | Page is the page the event is about, for every kind but ContextEventSnapshot. |
| FocusedPage? | *Page | FocusedPage is set for ContextEventPageClosed. |
| Url | string | Url and Title are set for ContextEventPageUpdated. |
| Title | string | |
| Captcha? | *CaptchaEvent | Captcha is set for ContextEventCaptchaDetected and ContextEventCaptchaResolved. |
| Reaction? | *ReactionEvent | Reaction is set for ContextEventReactionFired. |
ContextEventHandler
type aliastype ContextEventHandler = func(...)ContextEventHandler is called once per context event.
Calls are sequential and in the order the browser reported the changes, so the handler needs no locking of its own. It runs on a goroutine the SDK owns, not the caller's. A handler that blocks for long makes the server drop this reader's backlog and start over with a snapshot.
ContextEventKind
type aliastype ContextEventKind = intContextEventKind says what a ContextEvent reports, and so which of its fields are set.
CookiePartitionKey
structCookiePartitionKey describes CHIPS partitioning metadata for partitioned cookies.
| TopLevelSite | string | |
| HasCrossSiteAncestor | bool |
DbscSession
structDbscSession is one Device Bound Session Credentials entry.
| Site | string | Site is the serialized schemeful site key, e.g. "https://google.com". |
| Session | string | Session is base64 of the serialized DBSC Session proto (includes the wrapped binding key; portable under WRC's software key provider). |
DomChangeHandler
type aliastype DomChangeHandler = func(...)DomChangeHandler is called after the mirrored tree changed, including once for the opening snapshot. Read the new state from DomMirror.Root.
Calls are serialized on a goroutine the SDK owns, so the handler needs no locking of its own, and it is safe to call back into the mirror from it. Calls are also coalesced: several changes in quick succession may produce a single call, which always sees the newest tree. Treat it as "something moved, re-read the root" rather than as one call per edit.
DomChildren
structDomChildren is the reply to Page.GetDomChildren.
| Children | string | Children is a JSON array of DOM.Node. Empty for an id the mirror never handed out, which is also what a stale id from before a resync looks like. |
| Seq | uint64 | Seq is the page sequence this payload is valid as of. |
DomNode
structDomNode is a node in the mirrored page, in CDP's DOM.Node shape — the same shape Page.GetDOM returns, with two additions the mirror needs and a caller usually wants anyway: DomNode.FrameId and DomNode.ContentFrameId.
An <iframe> is an ordinary element here. The document it hosts is its one entry in Children, present once the element has been expanded, and nothing about walking the tree has to know a process boundary runs through it.
Nodes are immutable once handed out. The mirror applies a change by replacing the nodes from the root down to the one that moved, so a tree you took from DomMirror.Root stays a consistent snapshot while the mirror moves on, and unchanged subtrees keep their identity. Do not modify them.
| NodeId | int32 | |
| BackendNodeId | int32 | |
| NodeType | int32 | |
| NodeName | string | |
| LocalName | string | |
| NodeValue | string | |
| Attributes | []string | Attributes is flat name, value, name, value, ..., as CDP sends it. |
| ChildNodeCount | int32 | ChildNodeCount is the total children in the page, whether or not they are in Children. An <iframe> reports 1: the document it hosts. |
| Children | []*DomNode | Children is non-nil once the node has been expanded — empty and non-nil for a node that is expanded and has none. |
| ShadowRoots | []*DomNode | ShadowRoots holds author shadow roots, when the mirror was started with DomMirrorOptions.Pierce. |
| FrameId | string | FrameId is the frame this node lives in. Always set. Together with BackendNodeId this is the node's address: node ids are handed out per renderer and restart per frame, so two frames can and do use the same one, and the id on its own is ambiguous across a page. |
| ContentFrameId | string | ContentFrameId is set on an element that hosts a frame (<iframe>, <frame>, <object>): the frame it hosts, which is a different frame from FrameId and is the one its child document's ids belong to. |
DomPath
structDomPath is the reply to Page.RevealDomNode.
| Path | string | Path is a JSON array of DOM.Node, the main document first, each carrying one level of children, crossing into frames at the document nodes along it. Empty if the node is not on the page. |
| Seq | uint64 | Seq is the page sequence this payload is valid as of. |
DomResyncHandler
type aliastype DomResyncHandler = func(...)DomResyncHandler is called when the mirror had to be rebuilt, after the new tree is already in place. Rebuilding is automatic; this exists to tell a user why their expanded nodes collapsed.
The reason is one of "documentReplaced", "overflow", "rendererGone", "slowReader" or "manual", and is worth treating as an open set.
DomSnapshot
structDomSnapshot is the opening snapshot: the main frame's document. Child frames are not in it — their documents are fetched by expanding the <iframe> elements that host them, which is also what starts mirroring them.
| Root | string | Root is the main frame's document as CDP DOM.Node-shaped JSON, the same format GetDOM returns. |
| FrameId | string | FrameId is the page's main frame. |
| Seq | uint64 | Seq is the page sequence this snapshot is the baseline for. Every update after it carries a higher one. |
FocusedElement
structFocusedElement is a lightweight descriptor of an element — enough to identify it (and decide what to do) without another DOM round-trip. It names the element that stole focus in a FillError focus-loss failure.
| Ref? | *Locator | Ref names the element, ready to pass to an action such as Page.Click. Nil when it could not be named. |
| TagName | string | TagName is the upper-case tag name, e.g. "INPUT", "BUTTON", "DIV". |
| Id | string | Id is the id attribute, if present. |
| Name | string | Name is the name attribute, if present. |
| ClassName | string | ClassName is the class attribute, if present. |
| InputType | string | InputType is the <input> type, if the element is an <input>. |
| Text | string | Text is a whitespace-collapsed textContent/value snippet (max 120 chars). |
| Editable | bool | Editable is true when the element is itself an editable text sink (input / textarea / contenteditable). |
FrameRef
structFrameRef is the frame an element was found in. Every result that names an element carries one, so a call that searched the whole page says where its element lives.
| ID | string | ID is the frame's id, usable with FrameByID. It stays the same across navigations of the frame. |
| URL | string | URL is the URL of the document the frame showed when the element was found. |
| Main | bool | Main reports whether it is the page's main frame. |
Header
structHeader is a single HTTP header (name/value pair) on an intercepted request or response.
| Name | string | |
| Value | string |
HeaderModification
structHeaderModification is one entry passed to CloudBrowser.ModifyRequest. Build it as a plain struct literal.
| Action | HeaderModificationAction | Action selects what happens: HeaderModificationAdd inserts a new header, HeaderModificationEdit replaces an existing header's value, HeaderModificationRemove drops the header. |
| Name | string | Name is the header name the action applies to. |
| Value | string | Value is the header value for add/edit; ignored for remove. |
| Before | string | Before positions an "add" immediately before the named existing header; otherwise the header is appended at the end. Ignored for edit/remove. |
| After | string | After positions an "add" immediately after the named existing header. Mirror of Before; ignored for edit/remove. |
HeaderModificationAction
type aliastype HeaderModificationAction = stringHeaderModificationAction is the verb of a HeaderModification. Matches the add/edit/remove action strings; use the HeaderModificationXxx constants.
IceServer
structIceServer is one entry for a WebRTC RTCPeerConnection's ICE configuration: a TURN (or STUN) URL plus the short-lived credentials to authenticate with it. Pass these to your peer before creating the SDP offer.
| URLs | []string | URLs are the ICE server URLs (e.g. "turn:relay.example.com:3478?transport=udp"). |
| Username | string | Username is the short-lived TURN REST username (empty for plain STUN). |
| Credential | string | Credential is the short-lived TURN REST credential (empty for plain STUN). |
IdentityOption
type aliastype IdentityOption = func(...)IdentityOption customizes what GetClientIdentity folds into one call.
InterceptedRequest
structInterceptedRequest describes an outgoing request captured by a Request wait condition or CloudBrowser.WaitForAnyRequest.
| Method | string | |
| Url | string | |
| Headers | []Header | |
| Body | string | |
| ResourceType | string |
NetworkBodies
type aliastype NetworkBodies = stringNetworkBodies selects which response bodies network capture keeps. Kept bodies are not part of the exchange; read them with CloudBrowser.ReadNetworkBody.
NetworkBodyRange
structNetworkBodyRange is one range of a captured body, as returned by CloudBrowser.ReadNetworkBodyRange.
| Data | []byte | Data holds the bytes read; empty past the end of the body. |
| TotalSize | int64 | TotalSize is the number of bytes kept for the body as a whole. |
| Truncated | bool | Truncated matches the exchange's truncated flag for this body. |
NetworkExchange
structNetworkExchange is one request together with the response it received, as reported by CloudBrowser.CaptureNetwork.
A redirect chain arrives as one exchange per hop: the hops share ChainId and count up RedirectIndex, so a 302 and the request it points at are two exchanges, each with its own headers and status.
| RequestId | string | RequestId is unique per hop. |
| ChainId | string | ChainId is shared by every hop of one redirect chain. |
| RedirectIndex | int32 | RedirectIndex is 0 for the original request and counts up once per redirect followed. |
| FrameId | string | FrameId is the frame that issued the request; empty for worker traffic. |
| IsOOPIF | bool | IsOOPIF reports whether that frame runs in its own process. Capture happens in the browser process, so cross-process iframes are included. |
| ResourceType | NetworkResourceType | |
| Method | string | |
| Url | string | |
| InitiatorUrl | string | InitiatorUrl is the origin that started the request; empty when the browser itself did. |
| RequestHeaders | []Header | |
| RequestHeadersAreWire | bool | RequestHeadersAreWire reports whether RequestHeaders are the bytes actually sent — Cookie, User-Agent and Sec-* included — rather than what the page asked for before the network stack filled in the rest. |
| RequestBodyId | string | RequestBodyId names the request body; read it with CloudBrowser.ReadNetworkBody. Empty when the request had no body. Bodies never travel with the exchange. |
| RequestBodySize | int64 | RequestBodySize is the number of bytes kept for the request body. |
| RequestBodyTruncated | bool | RequestBodyTruncated reports that part of the request body is missing: it hit the per-body cap, or its source failed before all of it was read. File and streamed uploads are kept like any other body. |
| HasResponse | bool | HasResponse is false when the request failed before any response arrived; Error then says why. |
| StatusCode | int32 | |
| StatusText | string | |
| MimeType | string | |
| Protocol | string | Protocol is the negotiated ALPN protocol, e.g. "h2" or "http/1.1". |
| RemoteAddress | string | |
| ServedFrom | NetworkServedFrom | |
| ResponseHeaders | []Header | |
| ResponseHeadersAreWire | bool | |
| ResponseBodyId | string | ResponseBodyId names the response body; read it with CloudBrowser.ReadNetworkBody. Empty when body capture did not apply to this exchange — see NetworkCaptureOptions.Bodies. |
| ResponseBodySize | int64 | ResponseBodySize is the number of bytes kept for the response body, after content decoding. |
| ResponseBodyTruncated | bool | ResponseBodyTruncated reports that the kept body is shorter than the one the page received: it hit the per-body cap or the load ended early. |
| EncodedDataLength | int64 | |
| Error | string | Error is the net error name (e.g. "net::ERR_ABORTED"), empty on success. |
NetworkExchangeHandler
type aliastype NetworkExchangeHandler = func(...)NetworkExchangeHandler is called once per completed exchange.
Calls are sequential and in the order the browser finished the requests, so the hops of a redirect chain arrive in order and the handler needs no locking of its own. It runs on a goroutine the SDK owns, not the caller's.
Blocking here stalls the capture: the server buffers a bounded amount per reader and then drops its oldest entries, which NetworkCapture.Dropped reports. Hand slow work (disk, HTTP, a database) to another goroutine.
NetworkResourceType
type aliastype NetworkResourceType = stringNetworkResourceType is the kind of load an exchange belongs to. It is a string rather than a closed enum so an exchange from a newer browser still round-trips instead of decoding to an empty value; compare against the NetworkResource* constants.
NetworkServedFrom
type aliastype NetworkServedFrom = stringNetworkServedFrom says where an exchange's response came from.
ProxyConfig
structProxyConfig is the session's proxy as the browser uses it. An empty Host means a direct connection. Masque is the HTTP/3 MASQUE proxy, if any.
| Scheme | string | |
| Host | string | |
| Port | int | |
| Username | string | |
| Password | string | |
| Masque | string |
ProxyOption
type aliastype ProxyOption = func(...)ProxyOption sets an optional part of the proxy passed to CloudBrowser.SetProxy.
ProxyScheme
type aliastype ProxyScheme = stringProxyScheme is the protocol the browser speaks to its proxy.
ReactionEvent
structReactionEvent describes a reaction's click in a ContextEventReactionFired event.
| ReactionId | string | ReactionId is the id Page.AddReaction or CloudBrowser.AddReaction returned. |
| FrameId | string | FrameId is the frame the match was found in. |
| Success | bool | Success reports whether the click was carried out. |
| InterruptedCommand | string | InterruptedCommand is the action running on the page when the reaction acted ("fill", "type", "drag", ...), which waited until the click was done. Empty if none was. |
| Error? | *CommandError | Error is set iff Success is false, with the click's code: "not_found" (the click target was gone), "not_visible" (it hid again), "occluded_no_reachable_point", "occluded_after_evade" (something covered it) or "failed". A failed reaction is used up like one that clicked. |
Rect
structRect describes a position and size in CSS pixels.
| X | float64 | |
| Y | float64 | |
| Width | float64 | |
| Height | float64 |
RequestPattern
structRequestPattern matches a URL pattern in WaitForAnyRequest/Response. Set Abort to true to drop the request with an empty 200 response instead of letting it through to the network.
| URL | string | |
| Abort | bool |
ScriptEvent
structScriptEvent is one item on a session's script event stream. Exactly one of Log and Finished is set.
| RunId | string | RunId is the run that produced this event. |
| Log? | *ScriptLogEntry | Log is a console line the script printed. |
| Finished? | *ScriptFinished | Finished marks the end of the run. No further event for that run follows. |
ScriptEventHandler
type aliastype ScriptEventHandler = func(...)ScriptEventHandler is called once per script event.
Calls are sequential and in the order the browser produced them, so a run's last log line always arrives before its Finished and the handler needs no locking of its own. It runs on a goroutine the SDK owns, not the caller's.
Blocking here stalls delivery: the server buffers a bounded number of events per reader and then drops its oldest, which ScriptRun.Dropped reports. Hand slow work to another goroutine.
ScriptLogEntry
structScriptLogEntry is one console.* call from a script.
| Level | string | Level is "info", "warning" or "error", from console.log / .warn / .error. |
| Message | string | Message holds the logged arguments, already stringified the way console does it. |
| Timestamp | time.Time | Timestamp is when the script printed the line, stamped in the browser. |
SelectorMatch
structSelectorMatch says which of a CSS selector's matches a call took when it was not simply the first.
Where an element has to be visible (a CSS wait condition or reaction, and every action), a selector means its first rendered match: matches that are not rendered at all (display:none, visibility:hidden, no size) are passed over, so a hidden copy such as the one in a closed mobile menu does not shadow the visible element. A covered or offscreen match is still rendered and stays the target. Set only when the selector matched several elements and the call looked past the first: on a later match it took, or, with Index 0, when none of them is rendered.
| Index | int32 | Index is the 0-based position among the selector's matches in document order. |
| Count | int32 | Count is how many elements the selector matched. |
SessionUsage
structSessionUsage is what a session's browser has consumed since the session started: the CPU time and memory of every process that rendered its pages — main frames, cross-site iframes and the workers they host — including processes that have since exited. Work done on the session's behalf in processes it shares with other sessions is not included.
CloudBrowser.GetUsage reports it while the session runs, and CloudBrowser.StopBrowser returns the final figures, so there is no need to read it right before stopping.
| WallTime | float64 | WallTime is the real time since the session's browser was created, in seconds. |
| CpuTime | float64 | CpuTime is user plus kernel CPU time in seconds. Only time a thread actually ran on a core counts; waiting and idling do not. |
| MinMemory | int64 | MinMemory is the least memory the session held once its browser was ready, in bytes. Sampled about once a second. |
| AverageMemory | int64 | AverageMemory is the memory held, averaged over WallTime, in bytes; AverageMemory * WallTime is the memory-time used. Sampled about once a second, so short spikes count toward the peak but barely toward the average. |
| PeakMemory | int64 | PeakMemory is the most memory held at any one moment, in bytes. |
| RenderersUsed | int | RenderersUsed counts the renderer processes that hosted at least one of the session's frames: one per site its pages and cross-site iframes needed. |
| FramesCreated | int | FramesCreated counts the child frames created in the session's pages, whether or not they got a process of their own. |
| BytesReceived | int64 | BytesReceived is what the session's pages, workers and service workers received over the network, in bytes: HTTP responses with their headers, as transferred (before decompression), and WebSocket messages. Responses served from the browser's cache count nothing. A download in progress is counted while it runs, at most about a second behind. |
| BytesSent | int64 | BytesSent is what they sent the same way, in bytes: HTTP requests with headers and bodies, and WebSocket messages. |
StorageItem
structStorageItem is a single localStorage key/value pair.
| Key | string | |
| Value | string |
StorageOriginEntry
structStorageOriginEntry groups the localStorage entries of one origin (e.g. "https://example.com"). GetStorage returns these and SetStorage accepts the same shape, so a dump can be fed back verbatim.
| Origin | string | |
| Items | []StorageItem |
UaBrand
structUaBrand is one brand/version pair of the User-Agent client hints. For Brands the version is the significant (major) version; for FullVersionList the full version.
| Brand | string | |
| Version | string |
WaitArg
interfaceWaitArg is the marker interface for everything Wait accepts: a condition (a Locator, Captcha, Request or Response) or a wait-level option such as Timeout.
WaitCaptcha
structWaitCaptcha is the challenge a Captcha wait condition matched.
| Kind | string | Kind is the type of challenge, a short stable name such as "turnstile". |
| Frame | FrameRef | Frame is the frame the challenge was found in. |
WaitConditionStatus
structWaitConditionStatus is the per-condition diagnostic carried by WaitError when a Page.Wait times out: one entry per condition (in the order they were passed) explaining why it never matched.
| Index | int32 | Index into the condition list this entry describes. |
| State | string | State is the last observed state: "not_found", "found_hidden", "found_occluded" (only when the condition required visibility), "pending_steady", or "not_seen" for a Request / Response condition that never saw a matching request. |
| Ref? | *Locator | Ref names the element last seen for this condition; nil if it was never found or the match was not an element. |
| FrameId | string | FrameId where it was last seen (empty if never found). |
| ScopeError | string | ScopeError is set when the condition could not even be looked for at the last look, because a container given with Locator.In led nowhere: it says which link of the chain, and what was missing. State is "not_found" then. |
| IsVisible | bool | IsVisible reports whether it was CSS-visible at the last observation. |
| Bounds? | *Rect | Bounds is the last known rect in root-viewport coordinates (nil if never found). |
| Occluder? | *OccluderInfo | Occluder is the intercepting element, present iff State == "found_occluded". |
| SelectorMatch? | *SelectorMatch | SelectorMatch is set when the selector matched several elements and this status is about one other than the first, or none of them is rendered. |
WaitElement
structWaitElement is the element a CSS or JS wait condition matched.
| Ref? | *Locator | Ref names the matched element: pass it to any action to act on exactly this element, or to Locator.In to look inside it. No frame has to be named with it. Nil when a JS expression matched with a truthy value that is not an element. See Ref for how long it stays good. |
| Frame | FrameRef | Frame is the frame the element lives in (for a non-element match, the frame the expression ran in). |
| IsVisible | bool | IsVisible reports whether the element was visible at the match. |
| Bounds | Rect | Bounds is the element's rect in root-viewport CSS pixels. |
| SelectorMatch? | *SelectorMatch | SelectorMatch is set when a CSS condition matched an element other than the selector's first match. |
WaitKind
type aliastype WaitKind = stringWaitKind says what kind of condition matched a Page.Wait.