Documentation

Go SDK Reference

Module 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

CloudBrowser is the SDK-side handle for an active browserscale browser session.

One CloudBrowser corresponds to exactly one browser context, which is implicitly bound to its primary page server-side. The proto's page_id field is currently ignored server-side, so the SDK never sets it.

AcceptLanguage

method on CloudBrowser
AcceptLanguage()string

AcceptLanguage returns the Accept-Language header value the session was provisioned with.

Returns
string

ApiKey

method on CloudBrowser
ApiKey()string

ApiKey returns the API key used to rent this session.

Returns
string

ClearCookies

method on CloudBrowser
ClearCookies()

ClearCookies deletes every cookie in the browser context.

_ = browser.ClearCookies(ctx)
Throws
UNKNOWN_ERRORthe cookies could not be cleared

ClearStorage

method on CloudBrowser
ClearStorage(origin string)

ClearStorage deletes localStorage in the browser context.

Parameters
originstringif 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, "")
Throws
UNKNOWN_ERRORthe storage could not be cleared

Click

method on CloudBrowser
Click(target *Locator)*ElementResult

Click triggers a single left mouse click on the given target.

The browser scrolls the element into view if needed, moves the cursor along a human-like path, then dispatches a full mouseDown+mouseUp at a randomized point inside the element's bounding rect.

Parameters
target*Locatorlocator describing what to click; At is also valid
_, err := browser.Click(ctx, browserscale.CSS("button.submit"))
if err != nil {
    log.Fatal(err)
}
Returns
*ElementResult*ElementResult with success, resolved frameId, backendNodeId,
Throws
CLICK_FAILEDthe click could not be dispatched
ELEMENT_NOT_FOUNDno element matched the locator
FRAME_NOT_FOUNDthe requested frame does not exist
INVALID_LOCATORtarget is empty or has multiple targets set
PAGE_NOT_ALIVEthe page has been closed
TIMEOUTthe operation exceeded the server-side timeout
SeeCloudBrowser.ClickWith for right-click, double-click,

ClickWith

method on CloudBrowserinherits Click
ClickWith(target *Locator, opts ClickOpts)*ElementResult

ClickWith is the customizable variant of CloudBrowser.Click.

The browser scrolls the element into view if needed, moves the cursor along a human-like path, then dispatches a full mouseDown+mouseUp at a randomized point inside the element's bounding rect.

Parameters
target*Locatorlocator describing what to click; At is also valid
optsClickOptsclick customization; see ClickOpts
// Right double-click on a context menu trigger.
_, err := browser.ClickWith(ctx, browserscale.CSS("li.menu"), browserscale.ClickOpts{
    Button:     "right",
    ClickCount: 2,
})
Returns
*ElementResult*ElementResult with success, resolved frameId, backendNodeId,
Throws
CLICK_FAILEDthe click could not be dispatched
ELEMENT_NOT_FOUNDno element matched the locator
FRAME_NOT_FOUNDthe requested frame does not exist
INVALID_LOCATORtarget is empty or has multiple targets set
PAGE_NOT_ALIVEthe page has been closed
TIMEOUTthe operation exceeded the server-side timeout
SeeCloudBrowser.ClickWith for right-click, double-click,

Close

method on CloudBrowserinherits StopBrowser
Close()

Close is the defer-friendly alias for CloudBrowser.StopBrowser that uses a background context.

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.

browser, err := browserscale.RentBrowser(ctx, cfg)
if err != nil { log.Fatal(err) }
defer browser.Close()
Throws
UNKNOWN_ERRORthe stop API rejected the request

CountryCode

method on CloudBrowser
CountryCode()string

CountryCode returns the ISO-3166 country code the server allocated for this session (drives geo-IP and locale defaults).

Returns
string

DragBy

method on CloudBrowser
DragBy(target *Locator, offsetX float64, offsetY float64)*DragResult

DragBy picks up the target and drops it at an offset relative to the pickup point.

The browser presses the left mouse button at a pickup point inside the element, drags along a human-like path to (pickupX+offsetX, pickupY+offsetY), then releases. At is not a valid target — drag needs a real element.

Parameters
target*Locatorlocator describing the element to pick up
offsetXfloat64horizontal distance to drag, in CSS pixels
offsetYfloat64vertical distance to drag, in CSS pixels
_, err := browser.DragBy(ctx, browserscale.CSS(".slider .handle"), 120, 0)
if err != nil {
    log.Fatal(err)
}
Returns
*DragResult*DragResult with the resolved frameId, backendNodeId and the
Throws
UNKNOWN_ERRORthe drag could not be performed

DragTo

method on CloudBrowser
DragTo(target *Locator, absoluteX float64, absoluteY float64)*DragResult

DragTo picks up the target and drops it at absolute root-viewport coordinates.

Same gesture as CloudBrowser.DragBy, but the drop destination is in page coordinates rather than relative to the pickup point.

Parameters
target*Locatorlocator describing the element to pick up
absoluteXfloat64horizontal drop coordinate in the root viewport
absoluteYfloat64vertical drop coordinate in the root viewport
_, err := browser.DragTo(ctx, browserscale.CSS(".card"), 800, 400)
if err != nil {
    log.Fatal(err)
}
Returns
*DragResult*DragResult with the resolved frameId, backendNodeId and the
Throws
UNKNOWN_ERRORthe drag could not be performed

Evaluate

method on CloudBrowser
Evaluate(expression string)*EvaluateResult

Evaluate 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 (BackendNodeId, IsVisible, Bounds) is populated instead — use Node(id) in subsequent calls to act on it.

Parameters
expressionstringJavaScript expression evaluated in the main frame
res, err := browser.Evaluate(ctx, "document.title")
if err != nil {
    log.Fatal(err)
}
fmt.Println(res.Value)
Returns
*EvaluateResult*EvaluateResult with either Value (for non-Element returns) or
Throws
UNKNOWN_ERRORthe expression threw or could not be compiled

EvaluateInFrame

method on CloudBrowserinherits Evaluate
EvaluateInFrame(frameId string, expression string)*EvaluateResult

EvaluateInFrame runs a JavaScript expression in the given frame.

Same semantics as CloudBrowser.Evaluate but targets a specific frame instead of the main frame. Useful for evaluating inside OOPIFs (out-of- process iframes) found via CloudBrowser.GetPages.

Parameters
frameIdstringid of the frame to evaluate in; empty falls back to the main frame
expressionstringJavaScript expression evaluated in the main frame
pages, _ := browser.GetPages(ctx)
iframeId := pages[0].FrameTree.Children[0].FrameId
_, _ = browser.EvaluateInFrame(ctx, iframeId, "location.href")
Returns
*EvaluateResult*EvaluateResult with either Value (for non-Element returns) or
Throws
UNKNOWN_ERRORthe expression threw or could not be compiled

Fill

method on CloudBrowser
Fill(target *Locator, text string)*ElementResult

Fill clicks the target and types text into it, appending to any existing content.

The browser scrolls the element into view, moves the cursor along a human-like path, clicks to focus, then types the text character-by- character with QWERTZ keyboard simulation and human-like timing.

To overwrite the field instead of appending, use CloudBrowser.FillWith with ClearFirst: true.

At is not a valid target — Fill requires an actual element.

Parameters
target*Locatorlocator describing the input element
textstringtext to type into the element
_, err := browser.Fill(ctx, browserscale.CSS("input[name=email]"), "user@example.com")
Returns
*ElementResult*ElementResult with success, resolved frameId, backendNodeId
Throws
ELEMENT_NOT_FOUNDno element matched the locator
FILL_FAILEDthe input could not be filled
FRAME_NOT_FOUNDthe requested frame does not exist
INVALID_LOCATORtarget is empty or has multiple targets set
PAGE_NOT_ALIVEthe page has been closed
TIMEOUTthe operation exceeded the server-side timeout
SeeCloudBrowser.FillWith for clearing existing content or

FillWith

method on CloudBrowserinherits Fill
FillWith(target *Locator, text string, opts FillOpts)*ElementResult

FillWith is the customizable variant of CloudBrowser.Fill.

The browser scrolls the element into view, moves the cursor along a human-like path, clicks to focus, then types the text character-by- character with QWERTZ keyboard simulation and human-like timing.

To overwrite the field instead of appending, use CloudBrowser.FillWith with ClearFirst: true.

At is not a valid target — Fill requires an actual element.

Parameters
target*Locatorlocator describing the input element
textstringtext to type into the element
optsFillOptsfill customization; see FillOpts
// Wipe the field first, then type fresh content.
_, err := browser.FillWith(ctx, browserscale.CSS("input[name=email]"), "user@example.com", browserscale.FillOpts{
    ClearFirst: true,
})
Returns
*ElementResult*ElementResult with success, resolved frameId, backendNodeId
Throws
ELEMENT_NOT_FOUNDno element matched the locator
FILL_FAILEDthe input could not be filled
FRAME_NOT_FOUNDthe requested frame does not exist
INVALID_LOCATORtarget is empty or has multiple targets set
PAGE_NOT_ALIVEthe page has been closed
TIMEOUTthe operation exceeded the server-side timeout
SeeCloudBrowser.FillWith for clearing existing content or

Fingerprint

method on CloudBrowser
Fingerprint()string

Fingerprint returns the browser fingerprint id in use for this session.

Returns
string

GetCookies

method on CloudBrowser
GetCookies()[]CookieParam

GetCookies 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)
}
Returns
[]CookieParam[]CookieParam, one per cookie in the context
Throws
UNKNOWN_ERRORthe cookies could not be read

GetDOM

method on CloudBrowser
GetDOM(frameId string, depth int32)string

GetDOM 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 CloudBrowser.GetObservation instead.

Parameters
frameIdstringid of the frame to dump; empty targets the main frame
depthint32tree depth: -1 for the full tree, 0 for root only, N for
tree, err := browser.GetDOM(ctx, "", -1)
if err != nil {
    log.Fatal(err)
}
fmt.Println(tree)
Returns
stringJSON string in CDP DOM.Node shape
Throws
UNKNOWN_ERRORthe DOM could not be retrieved

GetDOMHash

method on CloudBrowser
GetDOMHash(frameId string)string

GetDOMHash 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 CloudBrowser.GetDOM only when the hash differs from your last snapshot.

Parameters
frameIdstringid of the frame to hash; empty targets the main frame
hash, err := browser.GetDOMHash(ctx, "")
if err != nil {
    log.Fatal(err)
}
if hash != lastHash {
    // DOM changed → re-fetch
}
Returns
string16-char hex string (the first 8 bytes of sha256 of the DOM JSON)
Throws
UNKNOWN_ERRORthe hash could not be computed

GetObservation

method on CloudBrowser
GetObservation(maxElementsPerFrame int32, maxTextLength int32)*ObservationResult

GetObservation returns a compact, agent-friendly description of every interactable element currently visible on the page, together with a truncated view of the surrounding text.

The result is intended as input for LLM/agent loops where a full DOM dump would be too large; the server filters down to elements that are actually visible and interactable.

Parameters
maxElementsPerFrameint32hard cap on how many elements the server
maxTextLengthint32hard cap on per-element text content length in
obs, err := browser.GetObservation(ctx, 200, 80)
if err != nil {
    log.Fatal(err)
}
fmt.Println(obs.Text)
Returns
*ObservationResult*ObservationResult with both a human-readable Text rendering
Throws
UNKNOWN_ERRORthe observation could not be produced

GetPages

method on CloudBrowser
GetPages()[]*PageInfo

GetPages returns all open pages (tabs and popups) for this session's browser context.

Each PageInfo carries the page's URL, title, viewport and a full nested frame tree (out-of-process iframes are children of the page's main frame).

pages, err := browser.GetPages(ctx)
if err != nil {
    log.Fatal(err)
}
for _, p := range pages {
    fmt.Println(p.Url, p.Title)
}
Returns
[]*PageInfo[]*PageInfo for every page currently open in the context
Throws
UNKNOWN_ERRORthe pages could not be enumerated

GetSelection

method on CloudBrowser
GetSelection()string

GetSelection 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 := browser.GetSelection(ctx)
if err != nil {
    log.Fatal(err)
}
fmt.Println("user selected:", sel)
Returns
stringthe selected text, or "" when nothing is selected
Throws
UNKNOWN_ERRORthe selection could not be read

GetStorage

method on CloudBrowser
GetStorage(origin string)[]StorageOriginEntry

GetStorage 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.

Parameters
originstringif 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)
    }
}
Returns
[]StorageOriginEntry[]StorageOriginEntry, one per origin with localStorage data
Throws
UNKNOWN_ERRORthe storage could not be read

GrpcUrl

method on CloudBrowser
GrpcUrl()string

GrpcUrl returns the gRPC endpoint the session is connected to.

Returns
string

HighlightNode

method on CloudBrowser
HighlightNode(backendNodeId int32, frameId string)

HighlightNode paints a debug overlay over the node identified by backendNodeId.

Useful for visual debugging of agent flows — the overlay stays until the next call. Pass backendNodeId <= 0 to clear any current highlights.

Parameters
backendNodeIdint32id of the node to highlight, or <= 0 to clear
frameIdstringid of the frame the node lives in; empty targets the main frame
if err := browser.HighlightNode(ctx, res.BackendNodeId, res.FrameId); err != nil {
    log.Fatal(err)
}
Throws
UNKNOWN_ERRORthe highlight could not be applied

InsertText

method on CloudBrowser
InsertText(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 CloudBrowser.Click or CloudBrowser.Fill first if you need a specific element to be focused.

Parameters
textstringthe text to insert at the caret
if err := browser.InsertText(ctx, "hello world"); err != nil {
    log.Fatal(err)
}
Throws
UNKNOWN_ERRORthe text could not be inserted

InspectAtPosition

method on CloudBrowser
InspectAtPosition(x float64, y float64)*InspectResult

InspectAtPosition 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.

Parameters
xfloat64viewport-relative x in CSS pixels
yfloat64viewport-relative y in CSS pixels
res, err := browser.InspectAtPosition(ctx, 200, 300)
if err != nil {
    log.Fatal(err)
}
fmt.Println(res.TagName, res.TextContent)
Returns
*InspectResult*InspectResult with the resolved backendNodeId, frameId, tag
Throws
UNKNOWN_ERRORthe hit-test failed

LoadHTML

method on CloudBrowser
LoadHTML(url string, html string, headers []Header, statusCode int32)

LoadHTML serves a synthetic response for the next navigation to url.

Registers a one-shot interceptor that intercepts the next request to url and replies with the supplied html and headers instead of going to the network. Useful for snapshotted pages, test fixtures, and offline replays. Pair with CloudBrowser.Navigate to trigger the load.

Parameters
urlstringthe URL pattern that, when navigated to, returns the html
htmlstringthe response body to serve
headers[]Headerextra response headers (Content-Type is set automatically)
statusCodeint32HTTP status code to serve; 0 means 200
_ = browser.LoadHTML(ctx, "https://example.com", "<h1>hi</h1>", nil, 0)
_, _ = browser.Navigate(ctx, "https://example.com", 0)
Throws
UNKNOWN_ERRORthe interceptor could not be installed

ModifyRequest

method on CloudBrowser
ModifyRequest(urlPattern string, body string, timeoutMs float64, mods []HeaderModification)*InterceptedRequest

ModifyRequest 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.

Parameters
urlPatternstringURL wildcard to wait for
bodystringreplacement request body; empty leaves the original body
timeoutMsfloat64per-call timeout in milliseconds; 0 uses the server default
mods[]HeaderModificationHeaderModification 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)
Returns
*InterceptedRequest*InterceptedRequest carrying the method/URL/headers/body that
Throws
UNKNOWN_ERRORno matching request appeared within the timeout

MoveTo

method on CloudBrowser
MoveTo(target *Locator)*ElementResult

MoveTo 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).

Parameters
target*Locatorlocator describing where to move; At is also valid
_, err := browser.MoveTo(ctx, browserscale.CSS("nav .menu"))
if err != nil {
    log.Fatal(err)
}
Returns
*ElementResult*ElementResult with the resolved frameId, backendNodeId,
Throws
UNKNOWN_ERRORthe move could not be completed

PressKey

method on CloudBrowser
PressKey(key string, code string, modifiers int32, location int32)

PressKey fires a single key-down event.

Only the keydown half is dispatched — pair with CloudBrowser.ReleaseKey for a full press cycle. The event targets whichever element currently has focus.

Parameters
keystringDOM KeyboardEvent.key value (e.g. "Enter", "a", "ArrowLeft")
codestringDOM KeyboardEvent.code value (e.g. "Enter", "KeyA"); empty falls back to key
modifiersint32bit-flag combination: Alt=1, Ctrl=2, Meta=4, Shift=8
locationint32DOM KeyboardEvent.location: 0=standard, 1=left, 2=right, 3=numpad
// Ctrl+A
_ = browser.PressKey(ctx, "a", "KeyA", 2, 0)
_ = browser.ReleaseKey(ctx, "a", "KeyA", 2, 0)
Throws
UNKNOWN_ERRORthe event could not be dispatched

ReadCanvas

method on CloudBrowser
ReadCanvas(target *Locator)*ReadCanvasResult

ReadCanvas 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.

Parameters
target*Locatorlocator for the <canvas>; CSS, JS or Node
res, err := browser.ReadCanvas(ctx, browserscale.CSS("#game canvas"))
if err != nil {
    log.Fatal(err)
}
img, _ := base64.StdEncoding.DecodeString(res.DataBase64)
os.WriteFile("canvas.png", img, 0o644)
Returns
*ReadCanvasResult*ReadCanvasResult with the base64 image in DataBase64, the canvas
Throws
ELEMENT_NOT_FOUNDno element matched the locator
FRAME_NOT_FOUNDthe requested frame does not exist
INVALID_LOCATORtarget is empty, uses At(x,y), or has multiple targets
PAGE_NOT_ALIVEthe page has been closed
TIMEOUTthe operation exceeded the server-side timeout
SeeCloudBrowser.ReadCanvasWith for format, quality, or a sub-rectangle

ReadCanvasWith

method on CloudBrowserinherits ReadCanvas
ReadCanvasWith(target *Locator, opts ReadCanvasOpts)*ReadCanvasResult

ReadCanvasWith is the customizable variant of CloudBrowser.ReadCanvas.

Parameters
target*Locatorlocator for the <canvas>; CSS, JS or Node
optsReadCanvasOptsformat, quality, sub-rectangle and frame override; see ReadCanvasOpts
// Read the left half of the canvas as JPEG at quality 80.
res, err := browser.ReadCanvasWith(ctx, browserscale.CSS("canvas"),
    browserscale.ReadCanvasOpts{Format: "jpeg", Quality: 80, SW: 150, SH: 300})
Returns
*ReadCanvasResult*ReadCanvasResult with the base64 image in DataBase64, the canvas
Throws
ELEMENT_NOT_FOUNDno element matched the locator
FRAME_NOT_FOUNDthe requested frame does not exist
INVALID_LOCATORtarget is empty, uses At(x,y), or has multiple targets
PAGE_NOT_ALIVEthe page has been closed
TIMEOUTthe operation exceeded the server-side timeout
SeeCloudBrowser.ReadCanvasWith for format, quality, or a sub-rectangle

ReleaseKey

method on CloudBrowserinherits PressKey
ReleaseKey(key string, code string, modifiers int32, location int32)

ReleaseKey fires a single key-up event.

Mirror of CloudBrowser.PressKey. Same parameter semantics; use this to close a press cycle that was started with PressKey.

Parameters
keystringDOM KeyboardEvent.key value (e.g. "Enter", "a", "ArrowLeft")
codestringDOM KeyboardEvent.code value (e.g. "Enter", "KeyA"); empty falls back to key
modifiersint32bit-flag combination: Alt=1, Ctrl=2, Meta=4, Shift=8
locationint32DOM KeyboardEvent.location: 0=standard, 1=left, 2=right, 3=numpad
_ = browser.PressKey(ctx, "Shift", "ShiftLeft", 0, 1)
_ = browser.ReleaseKey(ctx, "Shift", "ShiftLeft", 0, 1)
Throws
UNKNOWN_ERRORthe event could not be dispatched

Screenshot

method on CloudBrowser
Screenshot(format string, quality int32)*ScreenshotResult

Screenshot 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.

Parameters
formatstring"png" (default), "jpeg", or "webp"; pass "" for PNG
qualityint32encode quality 0-100 for "jpeg"/"webp" (ignored for
shot, err := browser.Screenshot(ctx, "png", 0)
if err != nil {
    log.Fatal(err)
}
img, _ := base64.StdEncoding.DecodeString(shot.DataBase64)
os.WriteFile("page.png", img, 0o644)
Returns
*ScreenshotResult*ScreenshotResult with the base64 image in DataBase64 and the
Throws
UNKNOWN_ERRORthe screenshot could not be captured

ScrollTo

method on CloudBrowser
ScrollTo(target *Locator)*ElementResult

ScrollTo 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.

Parameters
target*Locatorlocator describing the element to bring into view;
_, err := browser.ScrollTo(ctx, browserscale.CSS("#footer"))
if err != nil {
    log.Fatal(err)
}
Returns
*ElementResult*ElementResult with the resolved frameId, backendNodeId,
Throws
UNKNOWN_ERRORthe element could not be scrolled into view

SelectByIndex

method on CloudBrowser
SelectByIndex(target *Locator, index int32)*SelectOptionResult

SelectByIndex 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 CloudBrowser.SelectByIndexWith with SelectOpts.NoEvents).

At is not a valid target — Select requires an actual <select> element.

Parameters
target*Locatorlocator describing the <select> element
indexint32zero-based option index
_, err := browser.SelectByIndex(ctx, browserscale.CSS("select#country"), 2)
Returns
*SelectOptionResult*SelectOptionResult with the resolved selectedIndex,
Throws
ELEMENT_NOT_FOUNDno element matched the locator
FRAME_NOT_FOUNDthe requested frame does not exist
INVALID_LOCATORtarget is empty or has multiple targets set
PAGE_NOT_ALIVEthe page has been closed
SELECT_FAILEDthe option could not be selected
TIMEOUTthe operation exceeded the server-side timeout
SeeCloudBrowser.SelectByIndexWith for suppressing events or · CloudBrowser.SelectByValue, CloudBrowser.SelectByText

SelectByIndexWith

method on CloudBrowserinherits SelectByIndex
SelectByIndexWith(target *Locator, index int32, opts SelectOpts)*SelectOptionResult

SelectByIndexWith is the customizable variant of CloudBrowser.SelectByIndex.

Sets the option as selected on the targeted <select>, then fires the standard input + change events (unless suppressed via CloudBrowser.SelectByIndexWith with SelectOpts.NoEvents).

At is not a valid target — Select requires an actual <select> element.

Parameters
target*Locatorlocator describing the <select> element
indexint32zero-based option index
optsSelectOptsselect customization; see SelectOpts
// Pick the option silently, no input/change events.
_, err := browser.SelectByIndexWith(ctx, browserscale.CSS("select#hidden"), 0, browserscale.SelectOpts{
    NoEvents: true,
})
Returns
*SelectOptionResult*SelectOptionResult with the resolved selectedIndex,
Throws
ELEMENT_NOT_FOUNDno element matched the locator
FRAME_NOT_FOUNDthe requested frame does not exist
INVALID_LOCATORtarget is empty or has multiple targets set
PAGE_NOT_ALIVEthe page has been closed
SELECT_FAILEDthe option could not be selected
TIMEOUTthe operation exceeded the server-side timeout
SeeCloudBrowser.SelectByIndexWith for suppressing events or · CloudBrowser.SelectByValue, CloudBrowser.SelectByText

SelectByText

method on CloudBrowserinherits SelectByIndex
SelectByText(target *Locator, text string)*SelectOptionResult

SelectByText 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 CloudBrowser.SelectByIndexWith with SelectOpts.NoEvents).

At is not a valid target — Select requires an actual <select> element.

Parameters
target*Locatorlocator describing the <select> element
textstringthe visible option text to match
_, err := browser.SelectByText(ctx, browserscale.CSS("select#country"), "Germany")
Returns
*SelectOptionResult*SelectOptionResult with the resolved selectedIndex,
Throws
ELEMENT_NOT_FOUNDno element matched the locator
FRAME_NOT_FOUNDthe requested frame does not exist
INVALID_LOCATORtarget is empty or has multiple targets set
PAGE_NOT_ALIVEthe page has been closed
SELECT_FAILEDthe option could not be selected
TIMEOUTthe operation exceeded the server-side timeout
SeeCloudBrowser.SelectByIndexWith for suppressing events or · CloudBrowser.SelectByValue, CloudBrowser.SelectByText

SelectByTextWith

method on CloudBrowserinherits SelectByText
SelectByTextWith(target *Locator, text string, opts SelectOpts)*SelectOptionResult

SelectByTextWith is the customizable variant of CloudBrowser.SelectByText.

Sets the option as selected on the targeted <select>, then fires the standard input + change events (unless suppressed via CloudBrowser.SelectByIndexWith with SelectOpts.NoEvents).

At is not a valid target — Select requires an actual <select> element.

Parameters
target*Locatorlocator describing the <select> element
textstringthe visible option text to match
optsSelectOptsselect customization; see SelectOpts
_, err := browser.SelectByTextWith(ctx, browserscale.CSS("select#country"), "Germany", browserscale.SelectOpts{
    NoEvents: true,
})
Returns
*SelectOptionResult*SelectOptionResult with the resolved selectedIndex,
Throws
ELEMENT_NOT_FOUNDno element matched the locator
FRAME_NOT_FOUNDthe requested frame does not exist
INVALID_LOCATORtarget is empty or has multiple targets set
PAGE_NOT_ALIVEthe page has been closed
SELECT_FAILEDthe option could not be selected
TIMEOUTthe operation exceeded the server-side timeout
SeeCloudBrowser.SelectByIndexWith for suppressing events or · CloudBrowser.SelectByValue, CloudBrowser.SelectByText

SelectByValue

method on CloudBrowserinherits SelectByIndex
SelectByValue(target *Locator, value string)*SelectOptionResult

SelectByValue 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 CloudBrowser.SelectByIndexWith with SelectOpts.NoEvents).

At is not a valid target — Select requires an actual <select> element.

Parameters
target*Locatorlocator describing the <select> element
valuestringthe value attribute to match
_, err := browser.SelectByValue(ctx, browserscale.CSS("select#country"), "DE")
Returns
*SelectOptionResult*SelectOptionResult with the resolved selectedIndex,
Throws
ELEMENT_NOT_FOUNDno element matched the locator
FRAME_NOT_FOUNDthe requested frame does not exist
INVALID_LOCATORtarget is empty or has multiple targets set
PAGE_NOT_ALIVEthe page has been closed
SELECT_FAILEDthe option could not be selected
TIMEOUTthe operation exceeded the server-side timeout
SeeCloudBrowser.SelectByIndexWith for suppressing events or · CloudBrowser.SelectByValue, CloudBrowser.SelectByText

SelectByValueWith

method on CloudBrowserinherits SelectByValue
SelectByValueWith(target *Locator, value string, opts SelectOpts)*SelectOptionResult

SelectByValueWith is the customizable variant of CloudBrowser.SelectByValue.

Sets the option as selected on the targeted <select>, then fires the standard input + change events (unless suppressed via CloudBrowser.SelectByIndexWith with SelectOpts.NoEvents).

At is not a valid target — Select requires an actual <select> element.

Parameters
target*Locatorlocator describing the <select> element
valuestringthe value attribute to match
optsSelectOptsselect customization; see SelectOpts
_, err := browser.SelectByValueWith(ctx, browserscale.CSS("select#country"), "DE", browserscale.SelectOpts{
    NoEvents: true,
})
Returns
*SelectOptionResult*SelectOptionResult with the resolved selectedIndex,
Throws
ELEMENT_NOT_FOUNDno element matched the locator
FRAME_NOT_FOUNDthe requested frame does not exist
INVALID_LOCATORtarget is empty or has multiple targets set
PAGE_NOT_ALIVEthe page has been closed
SELECT_FAILEDthe option could not be selected
TIMEOUTthe operation exceeded the server-side timeout
SeeCloudBrowser.SelectByIndexWith for suppressing events or · CloudBrowser.SelectByValue, CloudBrowser.SelectByText

SessionId

method on CloudBrowser
SessionId()string

SessionId returns the unique server-assigned id for this browser session.

Returns
string

SetBlockList

method on CloudBrowser
SetBlockList(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.

Parameters
patterns[]stringURL wildcards to block; nil or empty clears the list
_ = browser.SetBlockList(ctx, []string{
    "*.doubleclick.net/*",
    "*googletagmanager.com*",
})
Throws
UNKNOWN_ERRORthe blocklist could not be applied

SetCookies

method on CloudBrowser
SetCookies(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.

Parameters
cookies[]CookieParamcookies 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,
    },
})
Throws
UNKNOWN_ERRORthe cookies could not be written

SetProxy

method on CloudBrowser
SetProxy(proxyHost string, proxyPort int32, proxyUsername string, proxyPassword string)

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.

Parameters
proxyHoststringupstream proxy host; empty disables the proxy
proxyPortint32upstream proxy port; ignored when proxyHost is empty
proxyUsernamestringproxy auth user (empty for unauthenticated proxies)
proxyPasswordstringproxy auth password (empty for unauthenticated proxies)
_ = browser.SetProxy(ctx, "proxy.example.com", 8080, "user", "pass")
Throws
UNKNOWN_ERRORthe proxy could not be applied

SetStaticPaths

method on CloudBrowser
SetStaticPaths(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.

Parameters
blobNamestringserver-side identifier of the snapshot to serve from
patterns[]stringURL wildcards to redirect to the cache; nil/empty disables
_ = browser.SetStaticPaths(ctx, "snap-2026-05", []string{"*.example.com/*"})
Throws
UNKNOWN_ERRORthe static paths could not be configured

SetStorage

method on CloudBrowser
SetStorage(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.

Parameters
storage[]StorageOriginEntryentries 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"},
        },
    },
})
Throws
UNKNOWN_ERRORthe storage could not be written

SolveCaptcha

method on CloudBrowser
SolveCaptcha(timeoutMs int32, retryAmount int32)string

SolveCaptcha 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 completed in-page server-side (the resulting token / bypass cookies are wired into the page automatically), so callers can ignore the returned string.

Parameters
timeoutMsint32how long to wait for a captcha to appear, in
retryAmountint32number of retries on a failed solve before giving up
if _, err := browser.SolveCaptcha(ctx, 0, 2); err != nil {
    log.Fatal(err)
}
Returns
stringempty string on success — the solution is applied server-side
Throws
UNKNOWN_ERRORno captcha appeared within timeoutMs, or the

Timezone

method on CloudBrowser
Timezone()string

Timezone returns the IANA timezone the session was provisioned with (e.g. "Europe/Berlin").

Returns
string

Wait

method on CloudBrowser
Wait(args ...WaitArg)*WaitResult

Wait blocks until any of the supplied locators matches.

Pass one or more Locators (built with CSS, JS, …) plus optional wait-level arguments such as Timeout. When several locators are supplied, the first one to match wins; the others are abandoned.

Defaults applied automatically: - timeout: DefaultWaitTimeoutMs (30s) — override with Timeout - per-locator visible/steady: DefaultVisible (true) and DefaultSteadyMs (500) for CSS and JS locators. For JS expressions returning a non-Element value (bool/string/number/object) both flags are no-ops. Override with Locator.Visible / Locator.Steady on individual locators.

Node and At are not valid wait conditions — they only make sense as action targets — and produce an error at send time.

Parameters
args...WaitArgone or more Locators plus optional wait-level options;
// Wait for either a success banner or a JS condition, max 5s.
_, err := browser.Wait(ctx,
    browserscale.CSS(".success"),
    browserscale.JS("window.__ready === true"),
    browserscale.Timeout(5000),
)
if err != nil {
    log.Fatal(err)
}
Returns
*WaitResult*WaitResult for the first matching condition (carries the
Throws
UNKNOWN_ERRORthe wait failed (no condition matched within the

WaitForAnyRequest

method on CloudBrowser
WaitForAnyRequest(timeoutMs float64, patterns []RequestPattern)int32, *InterceptedRequest

WaitForAnyRequest 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.

Parameters
timeoutMsfloat64per-call timeout in milliseconds; 0 uses the server default
patterns[]RequestPatternone 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)
Returns
int32, *InterceptedRequestint32 index of the matched pattern, *InterceptedRequest with
Throws
UNKNOWN_ERRORthe wait timed out or no patterns were supplied

WaitForAnyResponse

method on CloudBrowserinherits WaitForAnyRequest
WaitForAnyResponse(timeoutMs float64, patterns []RequestPattern)int32, *InterceptedResponse

WaitForAnyResponse 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.

Parameters
timeoutMsfloat64per-call timeout in milliseconds; 0 uses the server default
patterns[]RequestPatternone 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)
Returns
int32, *InterceptedResponseint32 index of the matched pattern, *InterceptedResponse with
Throws
UNKNOWN_ERRORthe wait timed out or no patterns were supplied

Locator

Locator is the universal "what element / what condition" type. It is used both as a wait condition (passed to Wait) and as a target for element actions (passed to Click, Fill, etc.).

Not every field is meaningful in every context: - selector / jsExpression → both wait and actions - backendNodeId → actions only (Wait rejects it) - visible / steadyTime → wait only (silently ignored by actions) - x / y → actions only (Wait rejects it) - frameId → both, may be overridden by call-level browserscale.InFrame() / browserscale.InAllFrames() options

Use the CSS / JS / Node / At constructors instead of building this struct by hand.

InAllFrames

method on Locator
InAllFrames()*Locator

InAllFrames scopes this Locator to every frame.

Equivalent to .InFrame(AllFrames). Use this when an element might appear inside any of several frames and you do not want to enumerate them.

_, _ = browser.Wait(ctx, browserscale.CSS("button.consent").InAllFrames())
Returns
*Locatorthe same Locator for chaining

InFrame

method on Locator
InFrame(id string)*Locator

InFrame scopes this Locator to a specific frameId.

Use the frameId from a previous result or CloudBrowser.GetPages to target elements inside a known iframe.

Parameters
idstringid of the frame to scope to
pages, _ := browser.GetPages(ctx)
iframeId := pages[0].FrameTree.Children[0].FrameId
_, _ = browser.Click(ctx, browserscale.CSS("button").InFrame(iframeId))
Returns
*Locatorthe same Locator for chaining

Steady

method on Locator
Steady(ms float64)*Locator

Steady requires the element to keep a stable position and size for at least ms milliseconds before the wait matches.

Pass 0 to disable the default DefaultSteadyMs (500). Has no effect for JS expressions that return a non-Element value, nor when the Locator is used as an action target.

Parameters
msfloat64steady-state duration in milliseconds; 0 disables
_, _ = browser.Wait(ctx, browserscale.CSS(".banner").Steady(0))
Returns
*Locatorthe same Locator for chaining

Visible

method on Locator
Visible(v bool)*Locator

Visible enforces or disables the visibility check for this Locator's wait condition.

Pass false to opt out of the default DefaultVisible (true). Has no effect when the Locator is used as an action target — actions never check visibility before dispatching.

Parameters
vbooltrue to require visibility, false to skip the check
_, _ = browser.Wait(ctx, browserscale.CSS("#hidden").Visible(false))
Returns
*Locatorthe same Locator for chaining

BrowserConfig

BrowserConfig holds all parameters for renting a browser session. Use NewBrowserConfig with the required fields, then chain optional setters.

UnstableWithFakeGpu

method on BrowserConfig
UnstableWithFakeGpu(renderer string, vendor string, extensions []string)*BrowserConfig

UnstableWithFakeGpu overrides WebGL UNMASKED_RENDERER_WEBGL, UNMASKED_VENDOR_WEBGL and getSupportedExtensions().

Unstable API — likely to be reshaped or removed without notice. Use only when you have a specific WebGL-fingerprint requirement.

Parameters
rendererstringvalue to return for UNMASKED_RENDERER_WEBGL
vendorstringvalue to return for UNMASKED_VENDOR_WEBGL
extensions[]stringlist returned by getSupportedExtensions()
cfg.UnstableWithFakeGpu("ANGLE", "Google Inc.", []string{"OES_texture_float"})
Returns
*BrowserConfigthe modified *BrowserConfig for chaining

WithCountryCode

method on BrowserConfig
WithCountryCode(countryCode string)*BrowserConfig

WithCountryCode 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.

Parameters
countryCodestringISO-3166 country code (e.g. "DE", "US")
cfg := browserscale.NewBrowserConfig(apiKey, 600, "", 0, "", "").WithCountryCode("DE")
Returns
*BrowserConfigthe modified *BrowserConfig for chaining

WithFingerprint

method on BrowserConfig
WithFingerprint(fingerprint string)*BrowserConfig

WithFingerprint 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.

Parameters
fingerprintstringserver-side fingerprint id
cfg := browserscale.NewBrowserConfig(apiKey, 600, "", 0, "", "").WithFingerprint("fp_abc123")
Returns
*BrowserConfigthe modified *BrowserConfig for chaining

WithTimezone

method on BrowserConfig
WithTimezone(timezone string)*BrowserConfig

WithTimezone sets the IANA timezone for the rented session.

Parameters
timezonestringIANA timezone (e.g. "Europe/Berlin")
cfg := browserscale.NewBrowserConfig(apiKey, 600, "", 0, "", "").WithTimezone("Europe/Berlin")
Returns
*BrowserConfigthe modified *BrowserConfig for chaining

Functions

At

function
At(x float64, y float64)*Locator

At 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 CloudBrowser.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.

Parameters
xfloat64viewport-relative x in CSS pixels
yfloat64viewport-relative y in CSS pixels
// Click at canvas-relative coordinates.
_, _ = browser.Click(ctx, browserscale.At(120, 240))
Returns
*Locator*Locator usable only as an action target

ConnectSession

function
ConnectSession(grpcUrl string, apiKey string, sessionId string)*CloudBrowser

ConnectSession 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.

Parameters
grpcUrlstringthe session's gRPC endpoint as returned by CloudBrowser.GrpcUrl,
apiKeystringAPI key authorizing access to the session
sessionIdstringid of the existing session to attach to
browser, err := browserscale.ConnectSession(ctx, "grpcs://api.browserscale.cloud:443", apiKey, sessionId)
if err != nil {
    log.Fatal(err)
}
defer browser.Close()
Returns
*CloudBrowser*CloudBrowser attached to the existing session; the returned
Throws
UNKNOWN_ERRORthe gRPC connection could not be opened

CSS

function
CSS(selector string)*Locator

CSS waits for / targets an element matching the given CSS selector.

When used in CloudBrowser.Wait, the returned Locator carries the SDK defaults DefaultVisible (true) and DefaultSteadyMs (500). 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.

Parameters
selectorstringCSS selector matching the element
// As a wait condition.
_, _ = browser.Wait(ctx, browserscale.CSS("button.submit"))
// As an action target.
_, _ = browser.Click(ctx, browserscale.CSS("button.submit"))
Returns
*Locator*Locator usable as a wait condition or as an action target

JS

function
JS(expression string)*Locator

JS waits for / targets the result of a JavaScript expression.

Same wait defaults as CSS (DefaultVisible=true, DefaultSteadyMs=500); these only apply when the expression returns a DOM Element. For non-Element truthy values (boolean, string, number, plain object) both fields 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.

Parameters
expressionstringJavaScript expression evaluated in the target frame
_, _ = browser.Wait(ctx, browserscale.JS("window.__ready === true"))
Returns
*Locator*Locator usable as a wait condition or as an action target

NewBrowserConfig

function
NewBrowserConfig(apiKey string, rentDuration int, proxyHost string, proxyPort int, proxyUsername string, proxyPassword string)*BrowserConfig

NewBrowserConfig returns a BrowserConfig populated with the required rental fields. Optional fields are configured via the chainable With… setters before passing the config to RentBrowser.

Parameters
apiKeystringAPI key authenticating the rental
rentDurationintlifetime of the session in seconds
proxyHoststringupstream proxy host (empty string disables the proxy)
proxyPortintupstream proxy port (ignored when proxyHost is empty)
proxyUsernamestringproxy auth user (empty for unauthenticated proxies)
proxyPasswordstringproxy auth password (empty for unauthenticated proxies)
cfg := browserscale.NewBrowserConfig("sk_…", 600, "", 0, "", "").
    WithCountryCode("DE").
    WithTimezone("Europe/Berlin")
Returns
*BrowserConfig*BrowserConfig ready to be customized further or passed to RentBrowser

Node

function
Node(backendNodeId int32)*Locator

Node targets an element by its DevTools backendNodeId.

Use this when you already have a backendNodeId from a previous result (e.g. WaitResult or EvaluateResult) and want to act on the exact same element without re-resolving by selector. Action-only — using it in CloudBrowser.Wait returns an error at send time.

Parameters
backendNodeIdint32DevTools backendNodeId of the target element
res, _ := browser.Click(ctx, browserscale.CSS("button.open"))
_, _ = browser.Click(ctx, browserscale.Node(res.BackendNodeId))
Returns
*Locator*Locator usable only as an action target

RentBrowser

function
RentBrowser(config *BrowserConfig)*CloudBrowser

RentBrowser 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.

Parameters
config*BrowserConfigrental 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()
Returns
*CloudBrowser*CloudBrowser ready to drive the rented session; call
Throws
UNKNOWN_ERRORthe rent API rejected the request or the gRPC

SetApiEndpoint

function
SetApiEndpoint(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.

Parameters
endpointstringbase URL of the rent/stop service, with no trailing slash
browserscale.SetApiEndpoint("https://browserscale.internal.example.com")

StopBrowser

function
StopBrowser(apiKey string, sessionId string)

StopBrowser 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.

Parameters
apiKeystringAPI key the session was rented with
sessionIdstringid of the session to release
_ = browserscale.StopBrowser(context.Background(), apiKey, sessionId)
Throws
UNKNOWN_ERRORthe stop API rejected the request

Timeout

function
Timeout(ms float64)WaitArg

Timeout overrides the CloudBrowser.Wait timeout.

When omitted, DefaultWaitTimeoutMs (30s) is used. Pass once per Wait call as one of the variadic arguments.

Parameters
msfloat64timeout in milliseconds
_, _ = browser.Wait(ctx, browserscale.CSS("#done"), browserscale.Timeout(5000))
Returns
WaitArga WaitArg suitable for passing to Wait

Types

ClickOpts

struct

ClickOpts customizes a CloudBrowser.ClickWith call. Zero/empty values mean "use the server default".

Fields
InFramestringInFrame overrides the locator's own frame. Empty = use the locator's frame (or the main frame if none). Pass a specific frameId, or AllFrames, to search elsewhere.
ButtonstringButton is the mouse button to use. Valid: "left" (default), "right", "middle".
ClickCountint32ClickCount controls single/double-click. 0 or 1 = single click (default), 2 = double-click.
ActionstringAction selects the mouse phase. "" or "click" = full mouseDown+mouseUp (default). "press" only dispatches mouseDown. "release" only dispatches mouseUp at the current cursor position.

CookieParam

struct

CookieParam 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.

Fields
Namestring
Valuestring
URL?*string
Domainstring
Pathstring
Secure?*bool
HTTPOnly?*bool
SameSite?*string
Expires?*float64
Priority?*string
SourceScheme?*string
SourcePort?*int
PartitionKey?*CookiePartitionKey

CookiePartitionKey

struct

CookiePartitionKey describes CHIPS partitioning metadata for partitioned cookies.

Fields
TopLevelSitestring
HasCrossSiteAncestorbool

DragResult

struct

DragResult is the outcome of a CloudBrowser.Drag gesture: the resolved source element and the start/end coordinates of the performed drag.

Fields
Successbool
FrameIdstring
BackendNodeIdint32
StartXfloat64
StartYfloat64
EndXfloat64
EndYfloat64

ElementResult

struct

ElementResult is the outcome of an element interaction such as CloudBrowser.Click, CloudBrowser.Fill or CloudBrowser.ScrollTo: the resolved element plus the root-relative coordinates the action was performed at.

Fields
Successbool
FrameIdstring
BackendNodeIdint32
IsVisiblebool
BoundsRect
RootXfloat64
RootYfloat64

EvaluateResult

struct

EvaluateResult carries the outcome of a JS evaluate call.

If the expression returned a DOM element, BackendNodeId/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.

Fields
Valueany
BackendNodeIdint32
IsVisiblebool
BoundsRect

FillOpts

struct

FillOpts customizes a CloudBrowser.FillWith call. Zero/empty values mean "use the server default".

Fields
InFramestringInFrame overrides the locator's own frame. Empty = use the locator's frame (or the main frame if none). Pass a specific frameId, or AllFrames, to search elsewhere.
ClearFirstboolClearFirst, when true, wipes the field's existing content with Ctrl+A, Delete before typing. Default (false) appends to whatever is already there.

FrameInfo

struct

FrameInfo describes a single frame within a page's frame tree.

Fields
FrameIdstring
Urlstring
IsOOPIFbool
HasJSContextbool
IsLoadingbool
IsVisiblebool
AbsoluteRectRect
RelativeRectRect
Children[]*FrameInfo

HeaderModification

struct

HeaderModification is one entry passed to CloudBrowser.ModifyRequest. Build it as a plain struct literal.

Fields
ActionHeaderModificationActionAction selects what happens: HeaderModificationAdd inserts a new header, HeaderModificationEdit replaces an existing header's value, HeaderModificationRemove drops the header.
NamestringName is the header name the action applies to.
ValuestringValue is the header value for add/edit; ignored for remove.
BeforestringBefore positions an "add" immediately before the named existing header; otherwise the header is appended at the end. Ignored for edit/remove.
AfterstringAfter positions an "add" immediately after the named existing header. Mirror of Before; ignored for edit/remove.

HeaderModificationAction

type alias
type HeaderModificationAction = string

HeaderModificationAction is the verb of a HeaderModification. Matches the add/edit/remove action strings; use the HeaderModificationXxx constants.

InspectResult

struct

InspectResult describes the topmost element hit at viewport-relative (x, y). BackendNodeId == 0 means nothing was found at that position.

Fields
BackendNodeIdint32
FrameIdstring
TagNamestring
TextContentstring
IsVisiblebool
BoundsRect

InterceptedRequest

struct

InterceptedRequest describes an outgoing request captured by CloudBrowser.WaitForAnyRequest.

Fields
Methodstring
Urlstring
Headers[]Header
Bodystring
ResourceTypestring

InterceptedResponse

struct

InterceptedResponse describes a network response captured by CloudBrowser.WaitForAnyResponse.

Fields
Urlstring
StatusCodeint32
Headers[]Header
Bodystring

ObservationResult

struct

ObservationResult is the compact page snapshot returned by CloudBrowser.GetObservation — the visible, interactive elements rendered as prompt-friendly text and as JSON.

Fields
Textstring
Jsonstring

PageInfo

struct

PageInfo describes an open page (tab or popup) inside a browser context.

Fields
PageIdstring
BrowserContextIdstring
Urlstring
Titlestring
ViewportRect
FrameTreeFrameInfo

ReadCanvasOpts

struct

ReadCanvasOpts customizes a CloudBrowser.ReadCanvasWith call. Zero/empty values mean "use the server default".

Fields
InFramestringInFrame overrides the locator's own frame. Empty = use the locator's frame (or the main frame if none). Pass a specific frameId, or AllFrames, to search elsewhere.
FormatstringFormat is the output encoding. "" or "png" (default), "jpeg", "webp", or "rgba" for the raw unpremultiplied RGBA pixel buffer.
Qualityint32Quality is the encode quality 0-100 for "jpeg"/"webp" (ignored otherwise). 0 = server default (90).
SXint32SX, 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.
SYint32SX, 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.
SWint32SX, 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.
SHint32SX, 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.

ReadCanvasResult

struct

ReadCanvasResult is the pixel readback of a <canvas>, returned by CloudBrowser.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).

Fields
Successbool
FrameIdstring
BackendNodeIdint32
DataBase64string
Widthint32
Heightint32
OriginCleanbool

Rect

struct

Rect describes a position and size in CSS pixels.

Fields
Xfloat64
Yfloat64
Widthfloat64
Heightfloat64

RequestPattern

struct

RequestPattern 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.

Fields
URLstring
Abortbool

ScreenshotResult

struct

ScreenshotResult is a single captured image of the page, returned by CloudBrowser.Screenshot. DataBase64 holds the encoded image bytes (PNG by default); Width and Height are in physical pixels.

Fields
DataBase64string
Widthint32
Heightint32

SelectOptionResult

struct

SelectOptionResult reports which <option> a SelectByXxx call ended up selecting.

Fields
SelectedIndexint32
SelectedValuestring
SelectedTextstring

SelectOpts

struct

SelectOpts customizes a SelectByXxxWith call. Zero/empty values mean "use the server default".

Fields
InFramestringInFrame overrides the locator's own frame. Empty = use the locator's frame (or the main frame if none). Pass a specific frameId, or AllFrames, to search elsewhere.
NoEventsboolNoEvents picks the option silently without firing input/change events. Default (false) fires the standard events.

StorageItem

struct

StorageItem is a single localStorage key/value pair.

Fields
Keystring
Valuestring

StorageOriginEntry

struct

StorageOriginEntry 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.

Fields
Originstring
Items[]StorageItem

WaitArg

interface

WaitArg is the marker interface for everything Wait accepts: a Locator (treated as a condition) or a wait-level option such as Timeout / InFrame / InAllFrames.

WaitResult

struct

WaitResult is the outcome of a CloudBrowser.Wait / CloudBrowser.WaitForAny call: which condition matched (Index, in argument order) and where the matched element lives.

Fields
Indexint32
FrameIdstring
BackendNodeIdint32
IsVisiblebool
BoundsRect