TypeScript SDK Reference

Package browserscale-ts. All methods return a Promise; the return types below show the resolved value (the Promise<…> wrapping is implicit).
class

CloudBrowser

38 methods

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

One CloudBrowser corresponds to exactly one browser context, which always has at least one page. Its own methods are what the pages share: proxy, cookies, storage, network rules and capture. Everything that acts on a document is a Page method; get the page from focusedPage, pages or getPage.

Construct via rentBrowser() / createWebSocketBrowser() — never directly.

addReaction

method on CloudBrowser
addReaction(match: Locator, opts: ReactionOpts | undefined): string

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 reactionFired event on CloudBrowser.contextEvents, carrying the page it fired on.

Parameters
matchLocatorthe css()/js() locator to watch for
optsReactionOpts | undefinedoptional reaction customization; see ReactionOpts
// Accept the consent banner on whichever page it shows up.
const id = await browser.addReaction(css("button#accept"));
Returns
stringthe reactionId (pass to CloudBrowser.removeReaction)
Throws
BrowserScaleError`match` (or `opts.on`) is not a css()/js() locator, or a server/transport error

captureNetwork

method on CloudBrowser
captureNetwork(opts: NetworkCaptureOptions, onExchange: NetworkExchangeHandler): NetworkCapture

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 resolves 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 resolves is missed. Call NetworkCapture.stop when done — it disarms the capture server-side, which an aborted transport alone does not.

Parameters
optsNetworkCaptureOptionswhich requests to capture and whether to keep bodies
onExchangeNetworkExchangeHandlercalled per exchange; see NetworkExchangeHandler for the ordering and blocking rules
const capture = await browser.captureNetwork(
{ patterns: ["*\/api/*"], bodies: "text" },
(ex) => console.log(ex.statusCode, ex.method, ex.url),
);
try {
await page.navigate("https://example.com");
} finally {
await capture.stop();
}
Returns
NetworkCaptureNetworkCapture handle for stopping the capture and inspecting how it ended

clearCookies

method on CloudBrowser
clearCookies(): void

Deletes every cookie in the browser context.

Rejects only on a transport failure - 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.

await browser.clearCookies();
Returns
void

clearStorage

method on CloudBrowser
clearStorage(origin: string | undefined): void

Deletes localStorage in the browser context.

Parameters
originstring | undefinedif set, only this origin's storage is deleted (e.g. "https://example.com"); omit to delete all origins
// Wipe one origin.
await browser.clearStorage("https://example.com");

// Wipe everything.
await browser.clearStorage();
Returns
void

contextEvents

method on CloudBrowser
contextEvents(onEvent: ContextEventHandler): ContextEvents

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 (captchaDetected, captchaResolved) and every reaction's click (reactionFired).

Resolves once the snapshot has been handed to onEvent; the events after it then arrive in the background. Call ContextEvents.stop when done.

Parameters
onEventContextEventHandlercalled per event; see ContextEventHandler for the ordering rules
const tabs = new Map<string, PageInfo>();
const listener = await browser.contextEvents((ev) => {
switch (ev.kind) {
  case "snapshot":
    tabs.clear();
    for (const p of ev.pages) tabs.set(p.page.id, p);
    break;
  case "pageOpened":
    tabs.set(ev.page.id, ev.info);
    break;
  case "pageClosed":
    tabs.delete(ev.page.id);
    break;
  case "pageUpdated": {
    const t = tabs.get(ev.page.id);
    if (t) Object.assign(t, { url: ev.url, title: ev.title });
    break;
  }
}
});
// later
await listener.stop();
Returns
ContextEventsContextEvents handle for stopping the listener and inspecting how it ended

createPage

method on CloudBrowser
createPage(): Page

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. Resolves once the page is ready for Page.navigate.

const page = await browser.createPage();
await page.navigate("https://example.com");
Returns
Throws
CommandErrorcreate_failed - the browser could not open the page, typically capacity

disableCaptchaAutoSolve

method on CloudBrowser
disableCaptchaAutoSolve(): boolean

Stops CloudBrowser.enableCaptchaAutoSolve. A solve already running finishes; one waiting for the focus is resolved with code "disabled".

await browser.disableCaptchaAutoSolve();
Returns
booleanwhether auto-solve was enabled

enableCaptchaAutoSolve

method on CloudBrowser
enableCaptchaAutoSolve(opts: CaptchaAutoSolveOpts | undefined): void

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 captchaDetected and then exactly one captchaResolved 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.

Parameters
optsCaptchaAutoSolveOpts | undefinedsettings; see CaptchaAutoSolveOpts. Omitted uses the defaults
await browser.enableCaptchaAutoSolve({ unfocused: "focus" });
// A captcha that shows up during the fill is solved, then the fill
// carries on.
const res = await page.fill(css("#email"), "user@example.com");
if (res.captchas) console.log(`held by ${res.captchas.length} solve(s)`);
Returns
void
Throws
BrowserScaleErroran `onFailure` or `unfocused` value other than the documented ones, or a negative number (rejected before anything is sent), or a transport failure

focusedPage

method on CloudBrowser
focusedPage(): Page

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.

const page = await browser.focusedPage();
await page.navigate("https://example.com");
Returns
Throws
NoPageErrorthe browser has no page yet; createPage opens the first

getApiKey

method on CloudBrowser
getApiKey(): string

Returns the API key used to rent this session.

Returns
string

getAuthSession

method on CloudBrowser
getAuthSession(): AuthSession | undefined

Exports the signed-in primary account and DBSC sessions of this browser context.

State is read in the browser process, so no page needs to be open. Returns undefined when the context has neither a signed-in account nor DBSC sessions.

const auth = await browser.getAuthSession();
if (auth) await fs.writeFile("auth.json", JSON.stringify(auth));
Returns
AuthSession | undefinedAuthSession, or undefined when there is nothing to export

getClientIdentity

method on CloudBrowser
getClientIdentity(opts: ClientIdentityOptions): ClientIdentity

Returns the session's client identity in one call: the User-Agent, the full UA client-hint set, the Accept-Language and the session's proxy — so an out-of-browser HTTP client can continue the session with matching request headers through the same proxy. With withCookies / withStorage the cookies and localStorage are folded into the same response.

The context configuration is read directly in the browser process, so no page needs to be open.

Parameters
optsClientIdentityOptionsoptionally fold in cookies / storage
const id = await browser.getClientIdentity({ withCookies: true });
console.log(id.userAgent, id.proxy.host, id.cookies?.length);
Returns
ClientIdentitythe session's ClientIdentity

getCookies

method on CloudBrowser
getCookies(): CookieParam[]

Returns all cookies currently stored in this session's browser context.

const cookies = await browser.getCookies();
for (const c of cookies) console.log(c.name, "=", c.value);
Returns
CookieParam[]CookieParam[], one per cookie in the context

getFingerprint

method on CloudBrowser
getFingerprint(): string

Returns the browser fingerprint id in use for this session.

Returns
string

getPage

method on CloudBrowser
getPage(pageId: string): Page

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.

Parameters
pageIdstringa page id, as reported by pages or an error
const page = browser.getPage(savedPageId);
await page.navigate("https://example.com");
Returns

getSessionId

method on CloudBrowser
getSessionId(): string

Returns the unique server-assigned id for this browser session.

Returns
string

getStorage

method on CloudBrowser
getStorage(origin: string | undefined): StorageOriginEntry[]

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
originstring | undefinedif set, only this origin is returned (e.g. "https://example.com"); omit to get all origins
const storage = await browser.getStorage();
for (const e of storage) {
for (const { key, value } of e.items) console.log(e.origin, key, "=", value);
}
Returns
StorageOriginEntry[]StorageOriginEntry[], one per origin with localStorage data

getStreamConfig

method on CloudBrowser
getStreamConfig(): IceServer[]

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

const ice = await browser.getStreamConfig();
const pc = new RTCPeerConnection({ iceServers: ice });
Returns
IceServer[]the ICE servers for the client RTCPeerConnection

getUsage

method on CloudBrowser
getUsage(): SessionUsage

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 resolves with them.

const before = await browser.getUsage();
await page.navigate("https://example.com");
const after = await browser.getUsage();
console.log(`navigation cost ${after.cpuTime - before.cpuTime}s of CPU`);
Returns
SessionUsageSessionUsage as of now

listReactions

method on CloudBrowser
listReactions(): ReactionInfo[]

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.

for (const r of await browser.listReactions()) console.log(r.reactionId);
Returns
ReactionInfo[]the reactions registered for every page

modifyRequest

method on CloudBrowser
modifyRequest(urlPattern: string, opts: {
      body?: string;
      modifications?: HeaderModification[];
      timeoutMs?: number;
    } | undefined): InterceptedRequest | null

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. Each modification is a plain HeaderModification object literal.

Parameters
urlPatternstringURL wildcard to wait for
opts{ body?: string; modifications?: HeaderModification[]; timeoutMs?: number; } | undefinedoptional body (replacement request body), modifications (header changes), and timeoutMs (per-call timeout)
const req = await browser.modifyRequest("*\/api/me", {
modifications: [
  { action: "add", name: "X-Trace", value: "abc123" },
  { action: "remove", name: "Cookie" },
],
timeoutMs: 5000,
});
console.log("forwarded headers:", req?.headers);
Returns
InterceptedRequest | nullInterceptedRequest carrying the method/URL/headers/body that were actually sent on the wire after modifications were applied; null when no request payload was reported
SeeCommandError for reading the code off the rejection

pages

method on CloudBrowser
pages(): PageInfo[]

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

Each PageInfo carries the Page to act on, the page's 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 (popup or tab, and its opener).

const pages = await browser.pages();
const popup = pages.find((p) => p.isPopup)?.page;
Returns
PageInfo[]PageInfo[] for every page currently open in the context

readNetworkBody

method on CloudBrowser
readNetworkBody(bodyId: string): NetworkBody

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.

Parameters
bodyIdstringrequestBodyId or responseBodyId from a NetworkExchange
const capture = await browser.captureNetwork(
{ patterns: ["*\/api/*"], bodies: "text" },
(ex) => {
  if (!ex.responseBodyId) return;
  void browser.readNetworkBody(ex.responseBodyId).then(({ data }) =>
    console.log(ex.url, new TextDecoder().decode(data)),
  );
},
);
Returns
NetworkBodythe body and whether the kept body is shorter than the original

readNetworkBodyRange

method on CloudBrowserinherits readNetworkBody
readNetworkBodyRange(bodyId: string, offset: number | undefined, length: number | undefined): NetworkBodyRange

Reads up to length bytes of a captured body starting at offset.

A single call returns at most 2 MiB; omit length to read that much. Loop on offset + data.length until it reaches totalSize to stream a large body.

Parameters
bodyIdstringrequestBodyId or responseBodyId from a NetworkExchange
offsetnumber | undefinedfirst byte to read (default 0)
lengthnumber | undefinedbytes to read (default and maximum 2 MiB)
Returns
NetworkBodyRangeNetworkBodyRange with the bytes and the body's total size

removeReaction

method on CloudBrowser
removeReaction(reactionId: string): boolean

Removes a reaction by id, wherever it is pending: a reaction from CloudBrowser.addReaction stops for every page, including the ones that open later. Returns false if no reaction with this id was pending anywhere.

Parameters
reactionIdstringid returned by CloudBrowser.addReaction or Page.addReaction
const removed = await browser.removeReaction(id);
Returns
booleantrue if a pending reaction with this id existed and was removed

setAuthSession

method on CloudBrowser
setAuthSession(session: AuthSession): void

Imports an auth session so the context comes up signed in (and syncing if syncConsent) with its DBSC sessions restored.

Call it before navigating. Pair with setCookies() / setStorage() to restore a full persona.

Parameters
sessionAuthSessionsession as returned by getAuthSession()
await browser.setAuthSession(saved);
await page.navigate("https://mail.google.com");
Returns
void

setBlockList

method on CloudBrowser
setBlockList(patterns: string[]): void

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 an empty array to clear the blocklist and let everything through.

Parameters
patternsstring[]URL wildcards to block; empty array clears the list
await browser.setBlockList([
"*.doubleclick.net/*",
"*googletagmanager.com*",
]);
Returns
void

setCookies

method on CloudBrowser
setCookies(cookies: CookieParam[]): void

Writes the supplied cookies into the browser context.

Existing cookies with the same (name, domain, path) tuple are overwritten. Pass an empty array for a no-op.

Parameters
cookiesCookieParam[]cookies to write; empty array is a no-op
await browser.setCookies([
{ name: "auth", value: "tok", domain: "example.com", path: "/" },
]);
Returns
void

setProxy

method on CloudBrowser
setProxy(proxyHost: string, proxyPort: number, proxyUsername: string, proxyPassword: string, options: ProxyOptions): void

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
proxyPortnumberupstream proxy port; ignored when proxyHost is empty
proxyUsernamestringproxy auth user; empty for unauthenticated proxies
proxyPasswordstringproxy auth password; empty for unauthenticated proxies
optionsProxyOptionsthe proxy's protocol and a MASQUE proxy, as for a rental
await browser.setProxy("proxy.example.com", 8080, "user", "pass");
await browser.setProxy("proxy.example.com", 1080, "user", "pass", { scheme: "socks5" });
Returns
void

setStaticPaths

method on CloudBrowser
setStaticPaths(blobName: string, patterns: string[]): void

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 is configured server-side. Pass an empty patterns array to disable caching for this session.

Parameters
blobNamestringserver-side identifier of the snapshot to serve from
patternsstring[]URL wildcards to redirect to the cache; empty disables
await browser.setStaticPaths("snap-2026-05", ["*.example.com/*"]);
Returns
void

setStorage

method on CloudBrowser
setStorage(storage: StorageOriginEntry[]): void

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
storageStorageOriginEntry[]entries to write, grouped by origin
await browser.setStorage([
{
  origin: "https://example.com",
  items: [
    { key: "token", value: "abc123" },
    { key: "theme", value: "dark" },
  ],
},
]);
Returns
void

startNetworkCapture

method on CloudBrowser
startNetworkCapture(opts: NetworkCaptureOptions): void

Arms a capture without subscribing to it.

Use it when the reader lives somewhere else — another tab, or a later createWebSocketBrowser against the same session. Most callers want CloudBrowser.captureNetwork instead, which arms and subscribes together. Calling this again replaces the running capture.

Parameters
optsNetworkCaptureOptionswhich requests to capture and whether to keep bodies
Returns
void

startStream

method on CloudBrowser
startStream(offerSdp: string): StreamAnswer

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 as {"type":"viewport","width":W,"height":H} on the reliable input channel. While the shown page closes, the last picture stays until the next page is shown; the stream keeps running.

Parameters
offerSdpstringyour RTCPeerConnection's SDP offer
const { answerSdp, viewport } = await browser.startStream(offer.sdp);
await pc.setRemoteDescription({ type: "answer", sdp: answerSdp });
Returns
StreamAnswerthe SDP answer to apply as the remote description, plus the viewport to map input coordinates into
Throws
NoPageErrorthe browser has no page to show yet; createPage opens the first
SeeCommandError for reading the code off the rejection

stopNetworkCapture

method on CloudBrowser
stopNetworkCapture(): boolean

Disarms the session's capture.

Returns
booleanwhether a capture was running

stopStream

method on CloudBrowser
stopStream(): void

Tears down the session's live video stream. Safe to call even if no stream is running.

Rejects only on a transport failure. Stopping a stream that is not running is a no-op rather than a failure, so there are no error codes to branch on.

await browser.stopStream();
Returns
void

streamNetworkExchanges

method on CloudBrowser
streamNetworkExchanges(onExchange: NetworkExchangeHandler): NetworkCapture

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.

Parameters
onExchangeNetworkExchangeHandlercalled per exchange; see NetworkExchangeHandler for the ordering and blocking rules
Returns
NetworkCaptureNetworkCapture attached to whatever capture is running; onExchange simply never fires when none is

waitForAnyRequest

method on CloudBrowser
waitForAnyRequest(patterns: RequestPattern[], opts: { timeoutMs?: number } | undefined): { index: number; request: InterceptedRequest | null }

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
patternsRequestPattern[]one or more URL patterns (with optional abort flags)
opts{ timeoutMs?: number } | undefinedoptional timeoutMs; omit to use the server default
const { index, request } = await browser.waitForAnyRequest(
[{ url: "*\/api/login" }],
{ timeoutMs: 5000 },
);
console.log(index, request?.method, request?.url);
Returns
{ index: number; request: InterceptedRequest | null }object with index (matched pattern index) and request (the captured method/URL/headers/body; null if intercepted with no body)
SeeCommandError for reading the code off the rejection

waitForAnyResponse

method on CloudBrowserinherits waitForAnyRequest
waitForAnyResponse(patterns: RequestPattern[], opts: { timeoutMs?: number } | undefined): { index: number; response: InterceptedResponse | null }

Blocks until the next response whose URL matches one of the supplied patterns is observed.

Same shape as waitForAnyRequest but on the response phase. When patternsi.abort is true the page receives an empty 200 instead of the real response.

Parameters
patternsRequestPattern[]one or more URL patterns (with optional abort flags)
opts{ timeoutMs?: number } | undefinedoptional timeoutMs; omit to use the server default
const { index, response } = await browser.waitForAnyResponse(
[{ url: "*\/api/login" }],
{ timeoutMs: 5000 },
);
console.log(index, response?.statusCode);
Returns
{ index: number; response: InterceptedResponse | null }object with index (matched pattern index) and response (the captured status/headers/body; null if no body was returned)
SeeCommandError for reading the code off the rejection
class

Locator

6 methods

Locator 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/Page.waitAny), 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). wait() additionally takes conditions that are not elements — captcha, request and response — which no action accepts.

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, frameById, 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.

Modifiers (in, visible, steady) are immutable — they return a new Locator and leave the original untouched, so it's safe to share a base locator or a container across calls.

Fields
selectorstring = ""
jsExpressionstring = ""
refValuestring = ""@internal The reference this locator stands for; read it with Locator.refString.
frameUrlPatternstring = ""@internal A frame, named directly. These only work as a container.
frameNameValue?string@internal
frameIdValuestring = ""@internal
isMainFrameboolean = false@internal
isAnyFrameboolean = false@internal
mustBeFrameboolean = false@internal The element has to hold a document of its own; see frame.
container?Locator@internal What this locator is looked for in; undefined for the default.
seenInstring = ""@internal The frame a reference was seen in, when it came out of a result. Lets a stale reference say where that frame is now.
visibleFlag?boolean
steadyMs?number
x?number
y?number

in

method on Locator
in(container: Locator): Locator

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.

Parameters
containerLocatorwhere to look
const pay = css("iframe[title='Secure payment']");
await page.fill(css("input[name=cardnumber]").in(pay), card);
await page.fill(css("input[name=cvc]").in(pay), cvc);
// A subtree, and a shadow host.
const dialog = css("[role=dialog]");
await page.click(css("button.close").in(dialog));
const picker = css("date-picker");
await page.click(css("button.next").in(picker));
// The iframe a wait found, as the place to look next.
const found = await page.wait(css("iframe.widget"));
await page.click(css("button").in(found.element.ref!));
Returns
Locatora new Locator for the same element, confined to the container

refString

method on Locator
refString(): string

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 this program.

const found = await page.wait(css(".result"));
const saved = found.element.ref!.refString();
// ... later, in the same session:
await page.click(ref(saved));
Returns
stringthe reference as text, or ""

steady

method on Locator
steady(ms: number): Locator

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 used as an action target.

Parameters
msnumbersteady-state duration in milliseconds; 0 disables
await page.wait(css(".banner").steady(0));
Returns
Locatora new Locator with the override applied

toJSON

method on Locator
toJSON(): string

Writes the locator as text, so that a result printed with JSON.stringify shows what its ref is: a reference as Locator.refString gives it, ready for ref, and any other locator as Locator.toString describes it.

Returns
string

toString

method on Locator
toString(): string

Describes the locator for logs and error messages: what it names and what it is looked for in, outermost last.

Returns
string

visible

method on Locator
visible(v: boolean): Locator

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 used as an action target — actions never check visibility before dispatching.

Parameters
vbooleantrue to require visibility, false to skip the check
await page.wait(css("#hidden").visible(false));
Returns
Locatora new Locator with the override applied
class

BrowserConfig

5 methods

Configuration for renting a browser session. Create with the required parameters, then chain optional setters.

Fields
apiKeystring
rentDurationnumber
proxyHoststring
proxyPortnumber
proxyUsernamestring
proxyPasswordstring

withCountryCode

method on BrowserConfig
withCountryCode(countryCode: string): BrowserConfig

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")
new BrowserConfig(apiKey, 600, "", 0, "", "").withCountryCode("DE");
Returns
BrowserConfigthis BrowserConfig for chaining

withFingerprint

method on BrowserConfig
withFingerprint(fingerprint: string): BrowserConfig

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
new BrowserConfig(apiKey, 600, "", 0, "", "").withFingerprint("fp_abc123");
Returns
BrowserConfigthis BrowserConfig for chaining

withMasque

method on BrowserConfig
withMasque(hostPort: string): BrowserConfig

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 the constructor.

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.

Parameters
hostPortstringthe MASQUE proxy as "host:port"
new BrowserConfig(apiKey, 600, "proxy.example.com", 8080, "user", "pass").withMasque("masque.example.com:443");
Returns
BrowserConfigthis BrowserConfig for chaining

withProxyScheme

method on BrowserConfig
withProxyScheme(scheme: ProxyScheme): BrowserConfig

Sets the protocol of the proxy passed to the constructor. Without it the proxy is an HTTP proxy.

Parameters
schemeProxyScheme"http" or "socks5"
new BrowserConfig(apiKey, 600, "proxy.example.com", 1080, "user", "pass").withProxyScheme("socks5");
Returns
BrowserConfigthis BrowserConfig for chaining

withTimezone

method on BrowserConfig
withTimezone(timezone: string): BrowserConfig

Sets the IANA timezone for the rented session.

Parameters
timezonestringIANA timezone (e.g. "Europe/Berlin")
new BrowserConfig(apiKey, 600, "", 0, "", "").withTimezone("Europe/Berlin");
Returns
BrowserConfigthis BrowserConfig for chaining
class

CaptchaCondition

1 method

CaptchaCondition is the wait condition built by captcha. It is accepted by Page.wait/Page.waitAny only — it is not a Locator, so no element action takes it.

in

method on CaptchaCondition
in(container: Locator): CaptchaCondition

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.

Parameters
containerLocatorwhere to look
// Only a challenge in the checkout frame, not the one in the chat widget.
const checkout = frameUrl("*checkout.example.com/*");
await page.wait(captcha().in(checkout));
Returns
CaptchaConditiona new CaptchaCondition confined to the container
class

ContextEvents

2 methods

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.

stop

method on ContextEvents
stop(): void

Ends the listener. Idempotent, and safe to call from a finally. Once it resolves the handler is no longer running.

Do not await it from inside the handler: it waits for the reader, which cannot finish while the handler it called is still running. Calling it there without awaiting is fine.

Returns
void

wait

method on ContextEvents
wait(): void

Resolves once the listener ends — ContextEvents.stop, a dead session or a transport failure.

Returns
void
class

DomMirror

9 methods

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. Underneath there is still one mirror per document, because a mutation observer is bound to a single Document and an out-of-process iframe is a different Document in a different process — but that is engine bookkeeping, not something a caller models.

Node ids restart per frame, so a node's address is the pair (DomNode.frameId, backendNodeId) and never the id alone.

The tree is treated as immutable: applying a change replaces the nodes from the root down to the one that moved and leaves every other object identical. A UI can therefore re-render from root and let React.memo (or any identity check) skip the parts that did not move.

``ts const mirror = await page.mirrorDom({ pierce: true }, () => render(mirror.root)); await mirror.expand(bodyNode); // start reporting changes inside <body> await mirror.collapse(bodyNode); // stop again await mirror.stop(); ``

collapse

method on DomMirror
collapse(node: DomNode): void

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.

Skipping this is not an error, it is a slow leak: the browser's revealed set only grows, and eventually it is no longer filtering anything.

Parameters
nodeDomNode
Returns
void
SeeCommandError for reading the code off the rejection

expand

method on DomMirror
expand(node: DomNode, depth: number | undefined): void

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.

Parameters
nodeDomNode
depthnumber | undefinedlevels below the node, default 1
Returns
void
SeeCommandError for reading the code off the rejection

getNode

method on DomMirror
getNode(frameId: string, backendNodeId: number): DomNode | undefined

Looks up a node by its address.

Parameters
frameIdstring
backendNodeIdnumber
Returns
DomNode | undefined

isExpanded

method on DomMirror
isExpanded(node: DomNode): boolean

Whether this node's children are known. Changes inside a node that is not expanded arrive only as an updated childNodeCount.

Parameters
nodeDomNode
Returns
boolean

locator

method on DomMirror
locator(node: DomNode): Locator

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.

Parameters
nodeDomNodea node of this mirror
const button = await mirror.locator(node);
await page.click(button);
Returns
LocatorLocator naming the node, usable as a target or a container

resync

method on DomMirror
resync(reason: DomResyncReason): void

Throws away the local copy of the whole page and fetches a fresh one. Happens automatically whenever the browser says the copy is void, so you rarely need to call it.

Parameters
reasonDomResyncReason
Returns
void
SeeCommandError for reading the code off the rejection

reveal

method on DomMirror
reveal(backendNodeId: number, frameId: string | undefined): DomNode[]

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

Parameters
backendNodeIdnumber
frameIdstring | undefined
Returns
DomNode[]the ancestor chain, the main document first, or an empty array if the node is not on the page
SeeCommandError for reading the code off the rejection

stop

method on DomMirror
stop(): void

Stops mirroring and detaches the reader. Idempotent, safe in a finally.

Returns
void

wait

method on DomMirror
wait(): void

Resolves once the mirror ends — stop(), a dead session, a transport failure.

Returns
void
class

NetworkCapture

2 methods

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

stop

method on NetworkCapture
stop(): void

Ends the capture. Idempotent, and safe to call from a finally.

Once it resolves the handler is no longer running, so data it collected is complete. 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 awaits the reader, which cannot finish while the handler it called is still running.

Rejects only on a transport failure, 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.

Returns
void

wait

method on NetworkCapture
wait(): void

Resolves once the capture ends — NetworkCapture.stop, a dead session or a transport failure.

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.

Returns
void
class

Page

48 methods

Page 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 rejects 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 — never construct it directly.

Fields
idstringThe page's id, stable for the life of the page.
browserCloudBrowserThe browser the page belongs to.

addReaction

method on Page
addReaction(match: Locator, opts: ReactionOpts | undefined): string

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 reactionFired event 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 .visible(false) to opt out of the default visibility gate. Pass a ReactionOpts to click a different target (on), change the button/click count, or the poll cadence.

Parameters
matchLocatorthe css()/js() locator to watch for
optsReactionOpts | undefinedoptional reaction customization; see ReactionOpts
// Auto-dismiss a consent button whenever it appears, in any frame.
const id = await page.addReaction(css("button#accept"));
// Only the one inside the consent provider's iframe.
const cmp = frameUrl("*consent.example.com/*");
const id = await page.addReaction(css("button.accept").in(cmp));
// Watch for a newsletter modal, but click its close "X" instead.
const id = await page.addReaction(css("#newsletter-modal"), {
on: css(".modal-close"),
});
Returns
stringthe reactionId (pass to Page.removeReaction)
Throws
BrowserScaleError`match` (or `opts.on`) is not a css()/js() locator, or a server/transport error

click

method on Page
click(target: Locator, opts: ClickOpts | undefined): ElementResult

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.

For right-click, double-click or press/release-only, pass a ClickOpts object as the second argument.

Parameters
targetLocatorlocator describing what to click; at is also valid
optsClickOpts | undefinedoptional click customization; see ClickOpts
try {
await page.click(css("button.submit"));
} catch (e) {
if (e instanceof ClickError) console.log(e.code, e.occluder?.tagName);
}
// Right double-click on a context menu trigger.
await page.click(css("li.menu"), { button: "right", clickCount: 2 });
Returns
ElementResultElementResult with success, the element's ref and frame, post-scroll isVisible, element bounds, and the root-viewport (rootX, rootY) where the click landed
Throws
BrowserScaleErrorinvalid locator, or a server/transport error (element not found, frame not found, timeout, page closed)
ClickErrorthe target was found but the click could not land because another element covered it; `.code`, `.occluder` and `.result` describe the blocker and the resolved coordinates. Code `"captcha_failed"`: a captcha appeared during the click and was not solved, with auto-solve set to `onFailure: "fail"` (CloudBrowser.enableCaptchaAutoSolve); `.result.captchas` lists it. Codes `"container_not_found"` (a container given with Locator.in is not on the page; the message names the link of the chain that was missing) and `"outside_scope"` (a js() target returned an element outside the element it was confined to) are about where the target was looked for, and every call with a target has them
StaleRefErrorthe target or a container is a reference whose element is gone (the call's own error, code `"stale_ref"`, is its `cause`)

close

method on Page
close(): Page

Closes the page the way closing its tab does. Its unload handlers run, but no "leave site?" prompt is shown. Resolves once the page is gone.

page = await popup.close();
Returns
Pagethe page that has the focus afterwards; when the closed page had it, the browser hands it on, usually to the page that opened it
SeeCommandError for reading the code off the rejection

dragBy

method on Page
dragBy(target: Locator, offsetX: number, offsetY: number): DragResult

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
targetLocatorlocator describing the element to pick up
offsetXnumberhorizontal distance to drag, in CSS pixels
offsetYnumbervertical distance to drag, in CSS pixels
await page.dragBy(css(".slider .handle"), 120, 0);
Returns
DragResultDragResult with the element's ref and frame and the final cursor position (rootX, rootY) where the drop happened
Throws
BrowserScaleErrorinvalid locator or a server/transport error
DragErrorthe source could not be acquired/pressed; `.code` and `.clickError` describe the underlying click-core failure. Code `"captcha_failed"`: a captcha appeared during the drag and was not solved, with auto-solve set to `onFailure: "fail"` (CloudBrowser.enableCaptchaAutoSolve). Codes `"container_not_found"` and `"outside_scope"`: as in click
StaleRefErrorthe target or a container is a reference whose element is gone (the call's own error, code `"stale_ref"`, is its `cause`)

dragTo

method on Page
dragTo(target: Locator, absoluteX: number, absoluteY: number): DragResult

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

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

Parameters
targetLocatorlocator describing the element to pick up
absoluteXnumberhorizontal drop coordinate in the root viewport
absoluteYnumbervertical drop coordinate in the root viewport
await page.dragTo(css(".card"), 800, 400);
Returns
DragResultDragResult with the element's ref and frame and the final cursor position (rootX, rootY) where the drop happened
Throws
BrowserScaleErrorinvalid locator or a server/transport error
DragErrorthe source could not be acquired/pressed; `.code` and `.clickError` describe the underlying click-core failure. Codes `"captcha_failed"`, `"container_not_found"` and `"outside_scope"`: as in dragBy
StaleRefErrorthe target or a container is a reference whose element is gone (the call's own error, code `"stale_ref"`, is its `cause`)

evaluate

method on Page
evaluate(expression: string, opts: EvaluateOpts | undefined): EvaluateResult<T>

Runs a JavaScript expression in the page's main frame.

The expression's return value is JSON-serialized server-side and parsed eagerly into .value. When the expression returns a DOM element the .value is null and the element metadata (ref, isVisible, bounds) is populated instead — pass the ref to subsequent calls to act on it.

The generic T is a TypeScript hint only — there is no runtime validation that the JS expression actually returned that type.

A promise is waited for: the call resolves when it settles, with the value it resolved to, and a rejected one rejects with a CommandError of code "threw". The wait ends after 30 s with "timeout"; opts 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 resolves normally; an expression that throws or will not compile rejects with a CommandError, so a typo can never read as "the page says null".

Parameters
expressionstringJavaScript expression evaluated in the main frame
optsEvaluateOpts | undefinedwhere the expression runs, how long a promise is waited for, or that it is not waited for; see EvaluateOpts
const res = await browser.evaluate<string>("document.title");
console.log(res.value);
// A promise is waited for; await works as well.
const items = await page.evaluate("fetch('/api/items').then(r => r.json())");
const count = await page.evaluate<number>("(await (await fetch('/api/items')).json()).length");
// Start work and come back to it: the first call resolves at once.
await page.evaluate("window.job = crawl(urls)", { noAwait: true });
// ... other steps ...
const rows = await page.evaluate("window.job", { timeoutMs: 300_000 });
// Telling a false answer from a broken expression.
try {
const res = await browser.evaluate<boolean>("window.__ready === true");
if (!res.value) { /* legitimately not ready yet *\/ }
} catch (e) {
if (e instanceof CommandError) throw new Error(`expression broken: ${e.message}`);
throw e;
}
Returns
EvaluateResult<T>EvaluateResult with either value (non-Element) or element metadata (Element)
Throws
CommandErrorcode `"threw"` (the expression raised, or the promise it answered with was rejected; the message carries the exception text), `"timeout"` (the promise did not settle in time; it goes on in the page), `"document_gone"` (the page navigated or reloaded, or the frame was removed, before the expression answered), `"not_run"` (it could not be compiled, or execution never started), `"aborted"` (the browser stopped execution) or `"no_context"` (the frame had no live script context). With `opts.in` also the codes of evaluateIn

evaluateIn

method on Pageinherits evaluate
evaluateIn(container: Locator, expression: string): EvaluateResult<T>

Runs a JavaScript expression inside a container: in the document of a frame, or scoped to an element.

Same semantics as 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 wait first when it may not be there yet. The result's frame says which frame the expression ran in.

Parameters
containerLocatorwhere the expression runs; see Locator.in
expressionstring
const pay = css("iframe[title='Secure payment']");
const title = await page.evaluateIn<string>(pay, "document.title");
// Scoped to an element: how many rows does this table have?
const rows = await page.evaluateIn<number>(css("table#orders"), "__wrc.scope.rows.length");
Returns
Throws
StaleRefErrorthe container is a reference whose element is gone

fill

method on Page
fill(target: Locator, text: string, opts: FillOpts | undefined): ElementResult

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 key by key on the keyboard layout of the session's region, with human-like timing.

To overwrite the field instead of appending, pass { clearFirst: true }.

at is not a valid target — fill requires an actual element.

Parameters
targetLocatorlocator describing the input element
textstringtext to type into the element
optsFillOpts | undefinedoptional fill customization; see FillOpts
await page.fill(css("input[name=email]"), "user@example.com");
// Wipe the field first, then type fresh content.
await page.fill(css("input[name=email]"), "user@example.com", { clearFirst: true });
Returns
ElementResultElementResult with success, the element's ref and frame and the root-viewport (rootX, rootY) where the element was clicked
Throws
BrowserScaleErrorinvalid locator, or a server/transport error (element not found, frame not found, timeout, page closed)
FillErrorthe field could not be focused/typed; `.code` and `.clickError` (the underlying click-core failure) describe why. Code `"captcha_failed"`: a captcha appeared during the fill and was not solved, with auto-solve set to `onFailure: "fail"` (CloudBrowser.enableCaptchaAutoSolve). Codes `"container_not_found"` and `"outside_scope"`: as in click
StaleRefErrorthe target or a container is a reference whose element is gone (the call's own error, code `"stale_ref"`, is its `cause`)

focus

method on Page
focus(): void

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.

await page.focus();
Returns
void
Throws
PageClosedErrorthe page has closed

followScript

method on Page
followScript(runId: string, onEvent: ScriptEventHandler): ScriptFollow

Watches script output on the page without starting anything.

For the case Page.startScript cannot cover: a run somebody else launched, or one this app started before it reloaded. 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.

Parameters
runIdstringrun to follow, or "" to follow every run on the page
onEventScriptEventHandlercalled per event; see ScriptEventHandler for the ordering and blocking rules
const follow = await page.followScript(runId, (ev) => {
if (ev.log) console.log(ev.log.message);
});
try {
await follow.wait();
} finally {
await follow.stop();
}
Returns
ScriptFollowScriptFollow handle for stopping the subscription

frames

method on Page
frames(): FrameInfo

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, hand its frameId to frameById.

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

const frames = await page.frames();
walkFrames(frames, (f, depth) => {
console.log("  ".repeat(depth) + f.url, f.name, f.isVisible);
});
Returns
FrameInfothe FrameInfo of the main frame, with its children
Throws
PageClosedErrorthe page has closed

getDOM

method on Page
getDOM(frameId: string, opts: GetDOMOpts | undefined): DOMResult

Returns the DOM 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 getObservation instead. The cheap polling endpoint is getDOMHash.

Parameters
frameIdstringid of the frame to dump; empty string targets the main frame
optsGetDOMOpts | undefinedoptional depth: -1 full tree (default), 0 root only, N root + N descendant levels
const { dom } = await page.getDOM();
Returns
DOMResultDOMResult with the JSON string in .dom (the .hash field is populated by getDOMHash, not by this call)

getDomChildren

method on Page
getDomChildren(backendNodeId: number, frameId: string, depth: number | undefined): { children: string; seq: number }

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> the one child is the document it hosts, and this call is what starts mirroring that frame.

An id that is simply unknown is not a failure: the call resolves with an empty result.

Parameters
backendNodeIdnumber
frameIdstring
depthnumber | undefined
Returns
{ children: string; seq: number }
SeeCommandError for reading the code off the rejection

getDOMHash

method on Page
getDOMHash(frameId: string): string

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

Parameters
frameIdstringid of the frame to hash; empty string targets the main frame
const hash = await page.getDOMHash();
if (hash !== lastHash) {
// DOM changed → re-fetch
}
Returns
string16-char hex string (the first 8 bytes of sha256 of the DOM JSON)

getDomRevision

method on Page
getDomRevision(frameId: string): number

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

Rejects only on a transport failure - 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.

Parameters
frameIdstring
Returns
number

getObservation

method on Page
getObservation(opts: GetObservationOpts | undefined): string

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

Parameters
optsGetObservationOpts | undefinedoptional format and budget overrides; see GetObservationOpts
const obs = await page.getObservation();
console.log(obs);
// Re-read just one form after the first full look.
const form = await page.getObservation({ scope: css("form#register") });
// Only what one frame shows.
const checkout = await page.getObservation({ scope: frameUrl("*checkout.example.com/*") });
Returns
stringthe observation in the requested format, ready to hand to a model
Throws
StaleRefErrorthe scope is a reference whose element is gone
SeeCommandError for reading the code off the rejection

getSelection

method on Page
getSelection(): string

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.

const sel = await page.getSelection();
console.log("user selected:", sel);
Returns
stringthe selected text, or "" when nothing is selected

highlight

method on Page
highlight(target: Locator | null): void

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

Parameters
targetLocator | nullthe ref of a result (or ref for one read from an observation); null clears the highlight
const found = await page.wait(css("button.submit"));
await page.highlight(found.element.ref!);
Returns
void
Throws
StaleRefErrorthe reference's element is gone

highlightNode

method on Page
highlightNode(backendNodeId: number, frameId: string): void

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 highlight with its ref.

The overlay stays until the next call. Pass backendNodeId <= 0 to clear any current highlights.

Parameters
backendNodeIdnumberid of the node to highlight, or <= 0 to clear
frameIdstringid of the frame the node lives in; empty string targets the main frame
await page.highlightNode(node.backendNodeId, node.frameId);
Returns
void

insertText

method on Page
insertText(text: string): void

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 click or fill first if you need a specific element to be focused.

Parameters
textstringthe text to insert at the caret
await page.insertText("hello world");
Returns
void
SeeCommandError for reading the code off the rejection

inspectAtPosition

method on Page
inspectAtPosition(x: number, y: number): InspectResult

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. An undefined ref (and a backendNodeId === 0) in the result means nothing was found.

Parameters
xnumberviewport-relative x in CSS pixels
ynumberviewport-relative y in CSS pixels
const r = await page.inspectAtPosition(200, 300);
console.log(r.tagName, r.textContent);
if (r.ref) await page.click(r.ref); // act on what is under the point
Returns
InspectResultInspectResult with the element's ref and frame, its address in the DOM mirror (backendNodeId, frameId), tag name, trimmed textContent, visibility and bounds

listReactions

method on Page
listReactions(): ReactionInfo[]

Returns the reactions still pending on the page, including those from CloudBrowser.addReaction that have not fired here yet (allPages is set on those). Reactions that have already fired on this page are not included.

const pending = await page.listReactions();
for (const r of pending) console.log(r.reactionId, String(r.match));
Returns
ReactionInfo[]the pending reactions for the page

listScriptRuns

method on Page
listScriptRuns(): ScriptRunInfo[]

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 page left behind, which Page.stopScripts needs an id to name.

for (const run of await page.listScriptRuns()) {
console.log(run.runId, run.runningMs);
}
Returns
ScriptRunInfo[]one entry per run still executing

loadHTML

method on Page
loadHTML(url: string, html: string, opts: LoadHTMLOpts | undefined): void

Navigates the page to url and serves html as the response.

The page navigates as with 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 resolves once the response was handed to the page, so wait for what the next step needs as after a navigation.

Parameters
urlstringthe URL the page will show the html under
htmlstringresponse body to serve
optsLoadHTMLOpts | undefinedoptional headers and statusCode (default 200)
await page.loadHTML("https://example.com", "<h1>hi</h1>");
await page.wait(css("h1"));
Returns
void
SeeCommandError for reading the code off the rejection

mirrorDom

method on Page
mirrorDom(opts: DomMirrorOptions, onChange: DomChangeHandler, onResync: DomResyncHandler | undefined): DomMirror

Starts a live copy of a frame's DOM and keeps it up to date.

The browser sends the top of the tree once, then reports only what changed in the part you expanded. Everything else costs a child count per batch, no matter how much churns inside it — which is what makes this usable on a page that rewrites a list sixty times a second, where re-fetching the document on a timer is not.

Expand and collapse as the user opens and closes nodes; that is what moves the boundary of what gets reported. The returned DomMirror holds the tree and exposes expand, collapse and reveal.

The handler runs after each applied batch. mirror.root is a new object whenever anything under it changed and the untouched parts keep their identity, so rendering straight from it with memoized components is cheap.

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.

``ts const mirror = await page.mirrorDom({ pierce: true }, () => { render(mirror.root); }); await mirror.expand(bodyNode); // ... await mirror.stop(); ``

Parameters
optsDomMirrorOptionsinitial depth and whether to pierce shadow roots
onChangeDomChangeHandlercalled after every change, including the first snapshot
onResyncDomResyncHandler | undefinedcalled when the copy had to be rebuilt, after the new tree is in place. Rebuilding is automatic; this is for telling the user why their expanded nodes collapsed.
Returns
SeeCommandError for reading the code off the rejection

moveTo

method on Page
moveTo(target: Locator): ElementResult

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 center (or to the viewport coordinate when target is at).

Parameters
targetLocatorlocator describing where to move; at is also valid
await page.moveTo(css("nav .menu"));
Returns
ElementResultElementResult with the element's ref and frame, post-scroll isVisible, element bounds and the root-viewport (rootX, rootY) where the cursor ended up
Throws
BrowserScaleErrorinvalid locator or a server/transport error
MoveErrorthe target could not be located (`.code` is `"not_found"`, or `"container_not_found"` / `"outside_scope"` as in click); `.result` carries the resolved payload
StaleRefErrorthe target or a container is a reference whose element is gone (the call's own error, code `"stale_ref"`, is its `cause`)

navigate

method on Page
navigate(url: string, opts: NavigateOpts | undefined): NavigateResult

Navigates the page to url.

Returns once the primary main-frame navigation commits (the response is received and a new document is selected), before DOMContentLoaded or load fire. Cross-origin redirects are followed.

Parameters
urlstringdestination URL
optsNavigateOpts | undefinedoptional navigation customization (e.g. timeoutMs)
await page.navigate("https://example.com");
Returns
NavigateResultNavigateResult with the final resolved URL and the frameId of the main frame after navigation
SeeCommandError for reading the code off the rejection

nodeRef

method on Page
nodeRef(backendNodeId: number, frameId: string): Locator

Turns the address of a DOM mirror node into a reference that click, fill and every other call with a target takes.

The mirror (mirrorDom) and 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 rejects with a StaleRefError when it is used.

Parameters
backendNodeIdnumberthe node's DomNode.backendNodeId
frameIdstringthe node's DomNode.frameId; empty is the main frame
const button = await page.nodeRef(node.backendNodeId, node.frameId);
await page.click(button);
Returns
LocatorLocator naming the node, usable as a target or a container
SeeCommandError for reading the code off the rejection · DomMirror.locator for the same from a mirror node

pressKey

method on Page
pressKey(key: string, opts: { code?: string; modifiers?: number; location?: number } | undefined): void

Fires a single key-down event.

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

Parameters
keystringDOM KeyboardEvent.key value (e.g. "Enter", "a", "ArrowLeft")
opts{ code?: string; modifiers?: number; location?: number } | undefinedoptional key customization: code (DOM KeyboardEvent.code, e.g. "KeyA"), modifiers (bit-flag: Alt=1, Ctrl=2, Meta=4, Shift=8), location (0=standard, 1=left, 2=right, 3=numpad)
// Ctrl+A
await page.pressKey("a", { code: "KeyA", modifiers: 2 });
await page.releaseKey("a", { code: "KeyA", modifiers: 2 });
Returns
void
SeeCommandError for reading the code off the rejection

readCanvas

method on Page
readCanvas(target: Locator, opts: ReadCanvasOpts | undefined): ReadCanvasResult

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.

at is not a valid target — a real <canvas> element is required.

Parameters
targetLocatorlocator for the <canvas>; css, js or a reference
optsReadCanvasOpts | undefinedoptional format, quality and sub-rectangle; see ReadCanvasOpts
const res = await page.readCanvas(css("#game canvas"));
await fs.writeFile("canvas.png", Buffer.from(res.dataBase64, "base64"));
// Read the left half as JPEG at quality 80.
const res = await page.readCanvas(css("canvas"), {
format: "jpeg", quality: 80, sw: 150, sh: 300,
});
Returns
ReadCanvasResultReadCanvasResult with the base64 image in dataBase64, the canvas width/height, the canvas's ref and frame and the originClean flag
Throws
StaleRefErrorthe target or a container is a reference whose element is gone
SeeCommandError for reading the code off the rejection

releaseDomSubtree

method on Page
releaseDomSubtree(backendNodeId: number, frameId: string): void

Stops reporting changes inside a node, and inside any frame below it. DomMirror.collapse calls this.

Parameters
backendNodeIdnumber
frameIdstring
Returns
void
SeeCommandError for reading the code off the rejection

releaseKey

method on Pageinherits pressKey
releaseKey(key: string, opts: { code?: string; modifiers?: number; location?: number } | undefined): void

Fires a single key-up event.

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

Parameters
keystring
opts{ code?: string; modifiers?: number; location?: number } | undefined
await page.pressKey("Shift", { code: "ShiftLeft", location: 1 });
await page.releaseKey("Shift", { code: "ShiftLeft", location: 1 });
Returns
void

removeReaction

method on Page
removeReaction(reactionId: string): boolean

Removes a pending reaction by id. 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.

Parameters
reactionIdstringid returned by Page.addReaction
const removed = await page.removeReaction(id);
Returns
booleantrue if a pending reaction with this id existed and was removed

revealDomNode

method on Page
revealDomNode(backendNodeId: number, frameId: string): { path: string; seq: number }

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.

An id that is simply unknown is not a failure: the call resolves with an empty result.

Parameters
backendNodeIdnumber
frameIdstring
Returns
{ path: string; seq: number }
SeeCommandError for reading the code off the rejection

runScript

method on Page
runScript(source: string): ScriptResult

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 waits for as long as the script runs, and cannot be bounded: the run id needed to cancel only arrives with the reply. Use Page.startScript when the script may outlive the caller's patience, or Page.stopScripts to abandon what is running on the page.

Parameters
sourcestringJavaScript to execute; its return value comes back as JSON
const result = await page.runScript(`
await page.navigate("https://example.com");
const items = [];
for (const el of await page.getDOM().querySelectorAll("h1")) {
  items.push(el.textContent);
}
return items;
`);
console.log(result.success, result.result);
Returns
ScriptResultthe return value and the script's whole console output. A script that threw is reported as success: false, not as a rejection

screenshot

method on Page
screenshot(opts: ScreenshotOpts | undefined): ScreenshotResult

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
optsScreenshotOpts | undefinedoptional format ("png" default, "jpeg", "webp") and quality (0-100, for jpeg/webp only); omit to use the server defaults
const shot = await page.screenshot({ format: "png" });
await fs.writeFile("page.png", Buffer.from(shot.dataBase64, "base64"));
Returns
ScreenshotResultScreenshotResult with the base64 image in dataBase64 and the physical pixel width/height
SeeCommandError for reading the code off the rejection

scrollTo

method on Page
scrollTo(target: Locator): ElementResult

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
targetLocatorlocator describing the element to bring into view; at is rejected
await page.scrollTo(css("#footer"));
Returns
ElementResultElementResult with the element's ref and frame, post-scroll isVisible and the element's bounds after the scroll
Throws
BrowserScaleErrorinvalid locator or a server/transport error
ScrollErrorthe target could not be located/scrolled (`.code` is `"not_found"`, or `"container_not_found"` / `"outside_scope"` as in click); `.result` carries the resolved payload
StaleRefErrorthe target or a container is a reference whose element is gone (the call's own error, code `"stale_ref"`, is its `cause`)

selectByIndex

method on Page
selectByIndex(target: Locator, index: number, opts: SelectOpts | undefined): SelectOptionResult

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 opts.fireEvents = false).

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

Parameters
targetLocatorlocator describing the <select> element
indexnumberzero-based option index
optsSelectOpts | undefinedoptional select customization; see SelectOpts
await page.selectByIndex(css("select#country"), 2);
// Pick the option silently, no input/change events.
await page.selectByIndex(css("select#hidden"), 0, { fireEvents: false });
Returns
SelectOptionResultSelectOptionResult with the resolved selectedIndex, selectedValue and selectedText after the change
Throws
BrowserScaleErrorinvalid locator, or a server/transport error (frame not found, timeout, page closed)
SelectOptionErrorthe option could not be selected; `.code` is `"not_found"` (no `<select>`), `"option_not_found"`, or `"container_not_found"` / `"outside_scope"` as in click
StaleRefErrorthe target or a container is a reference whose element is gone (the call's own error, code `"stale_ref"`, is its `cause`)

selectByText

method on Pageinherits selectByIndex
selectByText(target: Locator, text: string, opts: SelectOpts | undefined): SelectOptionResult

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 opts.fireEvents = false).

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

Parameters
targetLocatorlocator describing the <select> element
textstringthe visible option text to match
optsSelectOpts | undefinedoptional select customization; see SelectOpts
await page.selectByText(css("select#country"), "Germany");
Returns
SelectOptionResultSelectOptionResult with the resolved selectedIndex, selectedValue and selectedText after the change
Throws
BrowserScaleErrorinvalid locator, or a server/transport error (frame not found, timeout, page closed)
SelectOptionErrorthe option could not be selected; `.code` is `"not_found"` (no `<select>`), `"option_not_found"`, or `"container_not_found"` / `"outside_scope"` as in click
StaleRefErrorthe target or a container is a reference whose element is gone (the call's own error, code `"stale_ref"`, is its `cause`)

selectByValue

method on Pageinherits selectByIndex
selectByValue(target: Locator, value: string, opts: SelectOpts | undefined): SelectOptionResult

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 opts.fireEvents = false).

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

Parameters
targetLocatorlocator describing the <select> element
valuestringthe value attribute to match
optsSelectOpts | undefinedoptional select customization; see SelectOpts
await page.selectByValue(css("select#country"), "DE");
Returns
SelectOptionResultSelectOptionResult with the resolved selectedIndex, selectedValue and selectedText after the change
Throws
BrowserScaleErrorinvalid locator, or a server/transport error (frame not found, timeout, page closed)
SelectOptionErrorthe option could not be selected; `.code` is `"not_found"` (no `<select>`), `"option_not_found"`, or `"container_not_found"` / `"outside_scope"` as in click
StaleRefErrorthe target or a container is a reference whose element is gone (the call's own error, code `"stale_ref"`, is its `cause`)

solveCaptcha

method on Page
solveCaptcha(opts: { timeoutMs?: number; retryAmount?: number } | undefined): string

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.

Parameters
opts{ timeoutMs?: number; retryAmount?: number } | undefinedoptional timeoutMs (how long to wait for a captcha to appear; omit for server default 60s) and retryAmount (failures tolerated before giving up)
try {
await page.solveCaptcha({ retryAmount: 2 });
} catch (e) {
if (e instanceof SolveCaptchaError && e.code === "blocked") {
  // start over in a fresh session
}
throw e;
}
Returns
stringempty string on success — the solution is applied for you
Throws
SolveCaptchaErrorthe challenge was not solved, with a `code` and, when one was found, its `kind`:

startDomMirror

method on Page
startDomMirror(opts: DomMirrorOptions): DomSnapshot

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.

Parameters
optsDomMirrorOptions
SeeCommandError for reading the code off the rejection

startScript

method on Page
startScript(source: string, onEvent: ScriptEventHandler): ScriptRun

Launches source on the page and resolves 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 page. 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.

Parameters
sourcestringJavaScript to execute
onEventScriptEventHandlercalled per log line and once for the outcome; see ScriptEventHandler for the ordering and blocking rules
const run = await page.startScript(source, (ev) => {
if (ev.log) console.log(ev.log.level, ev.log.message);
});
const outcome = await run.wait();
Returns
ScriptRunScriptRun handle for awaiting or cancelling the run

stopDomMirror

method on Page
stopDomMirror(): void

Stops the page's mirror, every frame of it. Idempotent.

Returns
void

stopScripts

method on Page
stopScripts(runId: string): number

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 Page.runScript.

Parameters
runIdstringrun to cancel, or "" for all of them
await page.stopScripts(""); // abandon everything running
Returns
numberhow many runs were cancelled; 0 when the id named nothing in flight

type

method on Page
type(text: string, opts: { clearFirst?: boolean } | undefined): void

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 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 fill instead (strict, target-bound, per-key focus-verified).

Nothing is focused for you: click (or fill) the field first, or otherwise ensure focus, before calling type.

Parameters
textstringthe text to type as real key events
opts{ clearFirst?: boolean } | undefinedoptional: clearFirst clears the focused field (Ctrl+A, Delete) before typing
// OTP field that auto-advances across boxes.
await page.click(css("input.otp-0"));
await page.type("123456");
Returns
void

wait

method on Pageinherits waitAny
wait(condition: WaitCondition, opts: WaitOpts | undefined): WaitResult

Blocks until the given condition matches.

Shortcut for waitAny(condition, opts). See waitAny for the kinds of condition, timeout handling, per-locator visible/steady defaults and the locators that are not valid wait conditions.

With a single condition the kind of the result is known up front, so the return type is already narrowed: a locator yields element, request() yields request, and so on.

Parameters
conditionWaitConditionthe single condition to wait for
optsWaitOpts | undefined
const r = await page.wait(css(".success"));
console.log(r.element.bounds);
Returns

waitAny

method on Page
waitAny(conditions: WaitCondition[], opts: WaitOpts | undefined): WaitResult

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 first, trigger the action (click, solveCaptcha, navigate…), then await it.

The result's .index points to the entry in conditions that matched and .kind says which kind it was; narrow on kind to reach element, request or response.

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.

Defaults applied automatically: - timeout: 30000 ms — override via opts.timeoutMs - per-locator visible/steady: true / 500 for css() and js() locators. For js() expressions returning a non-Element value both flags are no-ops. Override with .visible(false) / .steady(ms) on individual locators.

A reference and at are not valid wait conditions — they only make sense as action targets — and throw at send time.

Parameters
conditionsWaitCondition[]one or more conditions to wait for; must be non-empty
optsWaitOpts | undefinedoptional wait customization (timeoutMs)
// Whatever comes first: the inbox, a captcha, or the error page.
const r = await page.waitAny(
[css("#inbox"), captcha(), request("https://example.com/error*")],
{ timeoutMs: 60000 },
);
if (r.kind === "captcha") await page.solveCaptcha();
else if (r.kind === "element") await page.click(r.element.ref!);
// Each condition with its own place to look.
const pay = css("iframe[title='Secure payment']");
const r = await page.waitAny([
css("#order-confirmed"),                 // whole page
css(".card-error").in(pay),              // only the payment frame
js("location.pathname === '/declined'"), // the top document
captcha(),                               // whole page
]);
// Start the wait first, then trigger the response it waits for.
const pending = page.wait(response("https://example.com/api/login*"));
await page.click(css("button[type=submit]"));
console.log((await pending).response.statusCode);
Returns
WaitResultWaitResult for the first matching condition
Throws
BrowserScaleErrora condition was invalid, or a server/transport error occurred
WaitErrorno condition matched before the deadline; `.conditions` holds the per-condition breakdown of why each never matched, with a `scopeError` naming a container that was never there
class

RequestCondition

1 method

RequestCondition is the wait condition built by request. It is accepted by Page.wait/Page.waitAny only.

Fields
urlPatternstring,
abortFlagboolean = false,

abort

method on RequestCondition
abort(v: boolean): RequestCondition

Drops the matching request: it is not sent, and the page receives an empty 200 instead. The request is still returned in the wait result.

Parameters
vbooleantrue (the default) to drop the request, false to only observe it
await page.wait(request("https://tracker.example.com/*").abort());
Returns
RequestConditiona new RequestCondition with the flag applied
class

ResponseCondition

1 method

ResponseCondition is the wait condition built by response. It is accepted by Page.wait/Page.waitAny only.

Fields
urlPatternstring,
abortFlagboolean = false,

abort

method on ResponseCondition
abort(v: boolean): ResponseCondition

Hides the matching response from the page: it receives an empty 200 instead. The real response is still returned in the wait result.

Parameters
vbooleantrue (the default) to hide the response, false to pass it through
await page.wait(response("https://example.com/api/token*").abort());
Returns
ResponseConditiona new ResponseCondition with the flag applied
class

ScriptFollow

2 methods

ScriptFollow is a read-only view of script output, returned by Page.followScript.

stop

method on ScriptFollow
stop(): void

Ends the subscription. Idempotent, and safe to call from a finally. It never cancels a run: other readers, and the script itself, are unaffected.

Returns
void

wait

method on ScriptFollow
wait(): void

Resolves once the subscription ends — ScriptFollow.stop, a dead session or a transport failure.

Returns
void
class

ScriptRun

3 methods

ScriptRun is a script running in the background, returned by Page.startScript. Its output is delivered to the handler passed there; this handle exists to await the outcome and to cancel the run.

detach

method on ScriptRun
detach(): void

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 page that started it.

Returns
void

stop

method on ScriptRun
stop(): void

Cancels the run and detaches this reader. Idempotent, and safe to call from a finally.

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.

Rejects only on a transport failure, and the local reader is detached regardless. Cancelling a run that has already finished is a no-op.

Returns
void

wait

method on ScriptRun
wait(): ScriptFinished

Resolves once the run ends, with how it ended.

A script that threw is an outcome, not an error: it resolves with success: false. It rejects when the run's fate is unknown — the stream broke or the session died before the script finished.

Returns
ScriptFinishedhow the script ended
class

WebSocketTransport

1 method

stream

method on WebSocketTransport
stream(method: DescMethodStreaming<I, O>, signal: AbortSignal | undefined, _timeoutMs: number | undefined, _header: HeadersInit | undefined, input: AsyncIterable<MessageInitShape<I>>, _contextValues: ContextValues | undefined): StreamResponse<I, O>

Runs a server-streaming call. Client-streaming is not supported: the frame format carries exactly one request message, and no RPC needs more.

Resolving means the server confirmed the subscription, so a caller may act on it — arm a network capture, say — without racing the first message.

Parameters
methodDescMethodStreaming<I, O>
signalAbortSignal | undefined
_timeoutMsnumber | undefined
_headerHeadersInit | undefined
inputAsyncIterable<MessageInitShape<I>>
_contextValuesContextValues | undefined
Returns
StreamResponse<I, O>

Functions

21 functions

Package-level functions: renting, listing, connecting to and stopping sessions, and the locator constructors.

anyFrame

function
anyFrame(): Locator

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

await page.wait(
js(`[...document.querySelectorAll('button')].find(b => b.innerText === 'Accept all')`)
  .in(anyFrame()),
);
Returns
LocatorLocator usable only as a container

at

function
at(x: number, y: number): 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 wait() throws at send time. Note that only click and moveTo accept at; scrollTo, drag, fill and select all require a real element.

Parameters
xnumberviewport-relative x in CSS pixels
ynumberviewport-relative y in CSS pixels
// Click at canvas-relative coordinates.
await page.click(at(120, 240));
Returns
LocatorLocator usable only as an action target

captcha

function
captcha(): CaptchaCondition

captcha 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 "captcha" 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.

const r = await page.waitAny([css("#inbox"), captcha()]);
if (r.kind === "captcha") await page.solveCaptcha();
Returns
CaptchaConditionCaptchaCondition usable only as a wait condition
connectSession(grpcUrl: string, apiKey: string, sessionId: string): CloudBrowser

Attaches to an already-rented session over a fresh gRPC connection.

Useful when a session id (and its gRPC URL) was persisted across processes and you want to drive it again without renting a new one. Mirrors browserscale-go's ConnectSession. Closing the returned handle via CloudBrowser.stopBrowser releases the rental (calls the stop endpoint) and closes the transport.

Parameters
grpcUrlstringsession host gRPC URL from the original rent (grpc:// or grpcs://)
apiKeystringAPI key the session was rented with
sessionIdstringid of the existing session
const browser = connectSession(grpcUrl, apiKey, sessionId);
try {
await page.navigate("https://example.com");
} finally {
await browser.stopBrowser();
}
Returns
CloudBrowserCloudBrowser attached to the existing session
createWebSocketBrowser(wsUrl: string, sessionId: string, apiKey: string, fingerprint: string): CloudBrowser

Attaches a CloudBrowser to an existing session over a raw WebSocket transport.

Use this from a browser context: the WebSocket transport framing is defined by WebSocketTransport and is served directly by the browserscale session host. The session must already exist server-side; unlike rentBrowser this does not call the rent API. Closing the returned handle (via CloudBrowser.stopBrowser) only closes the transport — the rental stays alive.

Parameters
wsUrlstringWebSocket URL (ws:// or wss://) of the session host
sessionIdstringid of the existing session
apiKeystringAPI key authorizing access to the session
fingerprintstringbrowser fingerprint id; empty if unknown
const browser = createWebSocketBrowser(
"wss://session-abc.browserscale.example.com/ws",
sessionId,
apiKey,
);
await page.navigate("https://example.com");
Returns
CloudBrowserCloudBrowser attached to the existing session

css

function
css(selector: string): Locator

css 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/Page.waitAny, 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 .visible(false) / .steady(ms) (use .steady(0) to disable the steady check).

When used as an action target (click, fill, …) 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.
await page.wait(css("button.submit"));
// As an action target. Found wherever it is, also inside an iframe.
const res = await page.click(css("button.accept"));
console.log(res.frame.main, res.frame.url);
Returns
LocatorLocator usable as a wait condition, an action target or a container

frame

function
frame(container: Locator): Locator

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

Parameters
containerLocatora css(), js() or reference locator
const pay = frame(css("iframe.pay"));
await page.fill(css("input[name=cardnumber]").in(pay), card);
Returns
LocatorLocator usable as a container

frameById

function
frameById(frameId: string): Locator

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

Parameters
frameIdstringthe frame's id
const found = await page.wait(css("#card"));
const title = await page.evaluateIn(frameById(found.element.frame.id), "document.title");
Returns
LocatorLocator usable only as a container

frameName

function
frameName(name: string): Locator

frameName names a frame by its name: window.name, which starts out as the iframe's name attribute. Otherwise as frameUrl.

Parameters
namestringthe frame's name
await page.fill(css("input[name=q]").in(frameName("search")), "shoes");
Returns
LocatorLocator usable only as a container

frameUrl

function
frameUrl(pattern: string): Locator

frameUrl names a frame by the URL of the document it shows.

It is a container: pass it to Locator.in, Page.evaluateIn or GetObservationOpts.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.

Parameters
patternstringURL wildcard; * matches any character span
const challenge = frameUrl("*hcaptcha.com/*frame=checkbox*");
await page.click(css("#checkbox").in(challenge));
// A frame inside a frame.
const outer = frameUrl("*\/_Incapsula_Resource*");
const inner = frameUrl("*hcaptcha.com/*frame=checkbox*").in(outer);
await page.click(css("#checkbox").in(inner));
Returns
LocatorLocator usable only as a container

js

function
js(expression: string): Locator

js 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 fields are no-ops and the condition matches as soon as the value is truthy. Use .visible(false) / .steady(0) to opt out.

Parameters
expressionstringJavaScript expression
await page.wait(js("window.__ready === true"));
// By text, inside one frame.
const pay = frameUrl("*checkout.example.com/*");
await page.click(
js(`[...document.querySelectorAll('button')].find(b => /Pay/.test(b.innerText))`).in(pay),
);
Returns
LocatorLocator usable as a wait condition, an action target or a container
listBrowsers(apiKey: string): BrowserInfo[]

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.

Each entry carries the grpcUrl it is driven from, so a listed session can be handed straight to connectSession. Only live sessions are listed; a stopped one is gone, not reported as ended.

Parameters
apiKeystringAPI key whose sessions to list
const browsers = await listBrowsers(apiKey);
for (const b of browsers) console.log(b.sessionId, b.countryCode);

// and to drive one of them
const browser = connectSession(browsers[0].grpcUrl, apiKey, browsers[0].sessionId);
Returns
BrowserInfo[]the running sessions, oldest first; empty when the key holds none

mainFrame

function
mainFrame(): Locator

mainFrame 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.
await page.click(css("button.accept").in(mainFrame()));
Returns
LocatorLocator usable only as a container

ref

function
ref(value: string): Locator

ref 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 rejects with a StaleRefError instead of acting on whatever took its place.

Parameters
valuestringthe reference, as Locator.refString returns it
const found = await page.wait(css(".result"));
await page.click(found.element.ref!);
// From an observation: row 47 of the frame whose header says "# ref @9F2C...".
await page.click(ref("47@9F2C41D0A1B24C7E8F3A5D6B7C8E9F01"));
Returns
LocatorLocator usable as an action target or a container

rentBrowser

function
rentBrowser(config: BrowserConfig): CloudBrowser

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. Closing the returned handle (via CloudBrowser.stopBrowser) also releases the rental.

Parameters
configBrowserConfigrental parameters
const cfg = new BrowserConfig("sk_…", 600, "", 0, "", "");
const browser = await rentBrowser(cfg);
try {
await page.navigate("https://example.com");
} finally {
await browser.stopBrowser();
}
Returns
CloudBrowserCloudBrowser ready to drive the rented session

request

function
request(urlPattern: string): RequestCondition

request 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, then await it. 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 "request" and request carries the method, URL, headers and body.

Parameters
urlPatternstringURL wildcard; * matches any character span
const pending = page.wait(request("https://example.com/api/submit*"));
await page.click(css("button[type=submit]"));
const r = await pending;
if (r.kind === "request") console.log(r.request.method, r.request.body);
Returns
RequestConditionRequestCondition usable only as a wait condition

response

function
response(urlPattern: string): ResponseCondition

response 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 "response" and response carries the status, headers and body.

Parameters
urlPatternstringURL wildcard, matched against the request URL
const pending = page.wait(response("https://example.com/api/token*"));
await page.click(css("#login"));
const r = await pending;
if (r.kind === "response") console.log(r.response.statusCode, r.response.body);
Returns
ResponseConditionResponseCondition usable only as a wait condition
setApiEndpoint(endpoint: string): void

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
setApiEndpoint("https://browserscale.internal.example.com");
Returns
void

stopBrowser

function
stopBrowser(apiKey: string, sessionId: string): SessionUsage | undefined

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
const usage = await stopBrowser(apiKey, sessionId);
Returns
SessionUsage | undefinedSessionUsage what the session consumed over its whole life; undefined when the server could not report it
throwCommandError(command: string, error: { code: string; message: string } | undefined): void

Raises the optional error of a uniform result, and does nothing when the command succeeded — so a call site stays one line instead of an if.

Parameters
commandstring
error{ code: string; message: string } | undefined
Returns
void

walkFrames

function
walkFrames(frame: FrameInfo, fn: (frame: FrameInfo, depth: number)): void

Calls fn for a 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.

Parameters
frameFrameInfowhere to start, usually what Page.frames returned
fn(frame: FrameInfo, depth: number)called with each frame and its depth below the start (0 for the start itself); return false to stop
const frames = await page.frames();
walkFrames(frames, (f, depth) => {
console.log("  ".repeat(depth) + f.url, f.name);
});
Returns
void

Errors

13 errors

Thrown by the command they belong to, each with a stable code and typed detail. Catch them with instanceof.

BrowserScaleError is the base class for every error thrown by the SDK. It wraps either: - a client-side validation failure (bad locator, missing patterns, …) - a server-side gRPC error (Connect's ConnectError, available as cause)

Semantic action failures (an occluded click, a wait timeout, an option that did not exist, …) are thrown as the typed subclasses below, each carrying the same structured detail the Go SDK exposes via errors.As — plus the partial result of the attempted action on .result, so a single catch gives you both the diagnostics and the resolved coordinates.

Catch the base for anything, or narrow to a subclass for the detail:

try { await page.click(css("#btn")); } catch (e) { if (e instanceof ClickError) console.log(e.code, e.occluder?.tagName); else if (e instanceof BrowserScaleError) { ... } }

ClickError is thrown by Page.click when the click did not land — the target was found but another element covered the intended point. occluder describes the blocker; result carries the resolved element and coordinates (success is false).

It is also nested under FillError / DragError as the underlying click-core failure; in that nested form result is undefined (the partial result lives on the outer error).

Fields
codestringMachine-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), "not_found", "not_visible" (found but not rendered, visibility:hidden or clipped away, so nothing covers it; a css selector already passes over matches that are not rendered, so with several matches none of them is) or "captcha_failed" (a captcha appeared during the click and auto-solve could not solve it, with onFailure: "fail"). Where the target was looked for has its own codes: "container_not_found" (a container given with Locator.in is not on the page; the message names the missing link), "outside_scope" (a js() target returned an element outside its container) and "stale_ref" (a reference whose element is gone; the call throws a StaleRefError around this error).
occluder?OccluderInfoThe intercepting element (present for occlusion codes).
evadeAttemptedbooleanWhether a pointer reposition was tried before giving up.
focusedPageId?stringFor code "page_not_focused", the page that has the focus. The call throws a PageNotFocusedError around this error then.
result?ElementResultResolved element + coordinates at the failed action. Present when this is the thrown top-level error; undefined when nested inside another error.

DragError is thrown by Page.dragBy / Page.dragTo 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 mirrors it and the full click diagnostics live under clickError. "captcha_failed": a captcha appeared during the drag and auto-solve could not solve it, with onFailure: "fail".

Fields
codestring
clickError?ClickError
resultDragResultResolved source + coordinates at the failed drag (success is false).

FillError is thrown by Page.fill when the field could not be focused/typed. The click-phase codes ("not_found", "not_visible", "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). "captcha_failed": a captcha appeared during the fill and auto-solve could not solve it, with onFailure: "fail". For untargeted stream typing that lets focus move (e.g. OTP), use Page.type.

Fields
codestringMachine-stable failure code (see the class doc for the full set).
clickError?ClickErrorThe underlying click-core failure that prevented focusing/typing. Present for the click-phase codes; undefined for "focus_stolen"/"focus_lost".
focusedBackendNodeId?numberNode that held focus when fill gave up (0 if nothing was focused), for the "focus_stolen"/"focus_lost" codes.
focusedElement?FocusedElementThe element that grabbed focus instead of the target ("focus_stolen"), so you can act on it (e.g. a consent button).
targetEditable?booleanThe 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.
targetValueLength?number
resultElementResultResolved element + coordinates at the failed action (success is false).

MoveError is thrown by Page.moveTo when the target could not be located. A move has no occlusion notion, so this is the only semantic failure.

Fields
codestring"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".
focusedPageId?stringFor code "page_not_focused", the page that has the focus. The call throws a PageNotFocusedError around this error then.
resultElementResult

NoPageError is thrown by the calls that need the focused page (CloudBrowser.focusedPage, CloudBrowser.startStream) while the browser has no page yet. A browser starts without one; CloudBrowser.createPage opens the first.

try { page = await browser.focusedPage(); } catch (e) { if (e instanceof NoPageError) page = await browser.createPage(); }

PageClosedError is thrown 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.

try { await page.click(css("#next")); } catch (e) { if (e instanceof PageClosedError) page = e.focusedPage; }

Fields
pageIdstringThe id of the page that closed.
focusedPagePageThe page that has the focus now.

PageNotFocusedError is thrown 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.

cause is the call's own error (ClickError, MoveError, FillError or DragError) with its partial result.

try { await page.click(css("atarget=_blank")); await page.click(css("#next")); } catch (e) { if (e instanceof PageNotFocusedError) page = e.focusedPage; // continue in the new tab }

Fields
focusedPagePageThe page that has the focus.

ScrollError is thrown by Page.scrollTo when the target could not be located/scrolled.

Fields
codestring"not_found", or one of the codes about where the target was looked for: "container_not_found", "outside_scope", "stale_ref".
resultElementResult

SelectOptionError is thrown by the Page.selectByIndex / selectByValue / selectByText calls when the option could not be selected. selectOption is programmatic (no pointer gate), so it only reports semantic failures.

Fields
codestring"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".
resultSelectOptionResult

SolveCaptchaError is thrown by Page.solveCaptcha when the challenge was not solved.

Fields
codestring"not_found" (no challenge waiting for an answer appeared; one that passed on its own does not count), "unsupported" (one was found that cannot be solved yet), "solve_failed" (it did not clear within retryAmount rounds), "blocked" (it was answered and the site replied with a block; solving again in this session will not help), "timeout", "page_closed" or "cancelled" (a navigation of the page started during the solve).
kindstringThe type of challenge found, a short stable name such as "turnstile"; empty when none was.
solveIdstringThe solve's id in the captchaDetected / captchaResolved events; empty when no solve ran.

StaleRefError is thrown 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.

cause is the call's own error (ClickError, FillError, CommandError, …), whose code is "stale_ref".

let found = await page.wait(css(".result")); try { await page.click(found.element.ref!); } catch (e) { if (!(e instanceof StaleRefError)) throw e; console.log("the page moved on to", e.url); found = await page.wait(css(".result")); }

Fields
ref?LocatorThe reference that went stale: the call's target, or the container it was to be looked for in.
urlstringWhere 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.

WaitError is thrown by Page.wait / Page.waitAny when no condition matched before the deadline. conditions holds the per-condition breakdown (same order/length as the conditions passed in) explaining why each one never matched; a condition whose container was never on the page says so in its scopeError.

Fields
codestringMachine-stable failure code, currently always "timeout".
conditionsWaitConditionStatus[]Per-condition status, same order/length as the conditions passed to wait.

Options

17 types

Optional settings a command accepts.

Settings for CloudBrowser.enableCaptchaAutoSolve. Omitted fields use the server defaults.

Fields
solveTimeoutMs?numberBudget for one solve, in milliseconds. Default 60000.
retryAmount?numberPer-solve retry cap, as in Page.solveCaptcha. Default: the solver's own.
onFailure?"fail" | "continue"What an action held by a solve does when the solve fails: "fail" (default) ends it with code "captcha_failed", "continue" lets it carry on as if the solve had succeeded.
unfocused?"wait" | "focus"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: "wait" (default) reports it (state "waiting_for_focus") and solves it once the page has the focus, "focus" brings the page to the front and solves it right away.
maxSolvesPerMinute?numberAt most this many solves 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. Default 5.

ClickOpts

interface

Optional customization for Page.click. All fields are optional; missing or zero values mean "use the server default".

Fields
button?ButtonMouse button. Default "left".
clickCount?number1 = single click (default), 2 = double-click.
action?ClickAction"click" (default) performs a full mouseDown+mouseUp. "press" only dispatches mouseDown, "release" only mouseUp at the current cursor position.

Options for CloudBrowser.getClientIdentity.

Fields
withCookies?booleanAlso return the session's cookies in ClientIdentity.cookies.
withStorage?booleanAlso return the session's localStorage in ClientIdentity.storage.
storageOrigin?stringWith withStorage, restrict to this origin (e.g. "https://example.com"). Omit to get all origins.

CookieParam

interface

CookieParam is one entry returned by getCookies() or passed to setCookies().

Fields
namestring
valuestring
url?string
domainstring
pathstring
secure?boolean
httpOnly?boolean
sameSite?string
expires?number
priority?string
sourceScheme?string
sourcePort?number
partitionKey?CookiePartitionKey

EvaluateOpts

interface

Optional customization for Page.evaluate.

Fields
in?LocatorWhere the expression runs, as the container of Page.evaluateIn: a frame, or an element the expression then sees as __wrc.scope. Omitted: the main document.
timeoutMs?numberHow long a promise the expression answers with is waited for, in ms. Omit for the default (30 000). After that the call rejects with "timeout" and the promise goes on in the page.
noAwait?booleantrue starts a promise without waiting for it: the call resolves 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

interface

Optional customization for Page.fill. All fields are optional; missing values mean "use the server default".

Fields
clearFirst?booleantrue wipes the field's existing content with Ctrl+A, Delete before typing. Default (false) appends to whatever is already in the field.
timeoutMs?numberBudget in ms to make the field focusable+clickable (locate, scroll, settle, un-occlude), mirroring the click timeout. Omit for the server default (5000). 0 makes fill one-shot (no retry).
steadyMs?numberSettle window in ms before the focus click, mirroring the click steady-time. Omit for the server default (750). 0 skips settling.

GetDOMOpts

interface

Depth used by getDOM(). 0 = whole tree (default), >0 = limited depth.

Fields
depth?number

Optional customization for Page.getObservation.

Fields
format?"text" | "json""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?numberCap on emitted elements per frame. Default 800 — a safety net against runaway documents; maxTotalTokens is the limit that normally binds.
maxTextLength?numberCap on human-readable strings (labels, text, values) in characters. Default 300. Identifier-like attributes (type, name, role) have their own fixed, shorter cap and are unaffected.
maxTotalTokens?numberBudget across ALL frames, in estimated tokens rather than characters — the same character count is worth roughly four times as many tokens in CJK text as in ASCII. 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?booleanInclude element bounds as bounds="x,y,w,h". 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?booleanOnly emit elements intersecting the frame's current viewport.
scope?LocatorObserves only part of the page, so a follow-up look at a form costs the form and not the ads around it. Omit for 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.

LoadHTMLOpts

interface

Optional customization for Page.loadHTML.

Fields
headers?{ name: string; value: string }[]Extra headers to attach to the synthetic response.
statusCode?numberDefault 200.

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.

Fields
patterns?string[]URL wildcards to capture; omit to capture every request the session makes. Prefix a pattern with "!" to exclude it, which is the short way to say "everything except this".
bodies?NetworkBodiesResponse-body capture. "text" keeps bodies whose MIME type is textual, "all" keeps every body, binary included. Defaults to "none", headers and status only. Request bodies are kept whenever a request has one.
bodyPatterns?string[]Narrows body capture to a subset of the captured requests; omit to apply bodies to all of them. Use it to log every request but only keep the payloads you care about.

ProxyOptions

interface

Optional parts of a proxy beyond host, port and credentials.

Fields
scheme?ProxySchemeThe proxy's protocol; "http" when omitted.
masque?stringA MASQUE proxy ("host:port") that carries HTTP/3 with the proxy's credentials. See BrowserConfig.withMasque.

ReactionOpts

interface

Optional customization for Page.addReaction and CloudBrowser.addReaction. All fields are optional; missing or zero values mean "use the server default".

Fields
on?LocatorOverride the click target. Omit to click the matched element itself. Provide a css()/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?ButtonMouse button for the click. Default "left".
clickCount?number1 = single click (default), 2 = double-click.
intervalMs?numberPoll cadence in milliseconds for the shared page loop. Default 300.

Optional customization for Page.readCanvas.

Fields
format?"png" | "jpeg" | "webp" | "rgba"Output encoding: "png" (default), "jpeg", "webp", or "rgba" for the raw unpremultiplied RGBA pixel buffer.
quality?numberEncode quality 0-100 for "jpeg"/"webp" (ignored otherwise). Default 90.
sx?numberOptional sub-rectangle in canvas pixels (mirrors getImageData(sx, sy, sw, sh)). The full canvas is read when sw/sh are omitted or <= 0.
sy?number
sw?number
sh?number

Optional customization for Page.screenshot.

Fields
format?"png" | "jpeg" | "webp"Image format: "png" (default), "jpeg", or "webp".
quality?numberEncode quality 0-100 for "jpeg"/"webp" (ignored for "png"). Default 90.

SelectOpts

interface

Optional customization for Page.selectByIndex, Page.selectByValue and Page.selectByText.

Fields
fireEvents?booleanfalse suppresses change/input events. Default (true) fires the standard events after the selection.

WaitOpts

interface

Optional customization for Page.wait / Page.waitAny.

Fields
timeoutMs?numberOmitted leaves it to the API, which defaults to 30 000 ms.

Results

25 types

What commands hand back.

BrowserInfo

interface

BrowserInfo describes one running session, as listBrowsers reports it.

Fields
sessionIdstring
grpcUrlstringThe endpoint this session is driven from — the same one rent returned. It is what makes a listed id usable: pass it to connectSession.
startTimenumberUnix seconds the session was rented at.
rentDurationnumberThe rental length in seconds; 0 means unlimited.
remainingSeconds?numberSeconds left on the rental, and undefined for an unlimited one — there is nothing to count down.
countryCodestring
timezonestring
proxyHoststring
publicIpstringThe address the session egresses from.
gpuIndex?numberThe physical card the session renders on, and undefined on a software-rendered host.

DOMResult

interface

DOMResult is the full-tree DOM snapshot returned by Page.getDOM, plus its sha256:8 hash for cheap change detection.

Fields
hashstring
domstring

DragResult

interface

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

Fields
successboolean
ref?LocatorNames the dragged element, and frame the frame it was found in; as in ElementResult.
frameFrameRef
startXnumber
startYnumber
endXnumber
endYnumber
captchas?CaptchaInterruption[]The captcha solves that held the drag, in order. Absent if none did.
selectorMatch?SelectorMatchSet when a css source resolved to other than the selector's first match.

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

Fields
successboolean
ref?LocatorNames 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. Undefined for a call that was given coordinates (at). See ref for how long it stays good.
frameFrameRefThe 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.
isVisibleboolean
boundsRect
rootXnumber
rootYnumber
captchas?CaptchaInterruption[]The captcha solves that held a Page.click or Page.fill while it ran, in order (see CloudBrowser.enableCaptchaAutoSolve). Absent if none did, and always absent for the other actions.
selectorMatch?SelectorMatchSet when a css target resolved to other than the selector's first match.

EvaluateResult carries the outcome of a JS evaluate call.

If the expression returned a DOM element, ref/isVisible/bounds are populated and value is null. Otherwise value holds the parsed JSON value (string/number/boolean/array/object/null). On parse failure value falls back to the raw server string so the caller is never empty-handed.

The optional generic T types the .value field for convenience — this is purely a TS hint, not a runtime guarantee.

Fields
successbooleanFalse only when the expression never produced a value, which rejects the call — so a resolved result always has this true. An expression that answers falsy is a successful evaluation, so this does not mean "the answer was false".
valueT
ref?LocatorNames the element the expression returned, ready to pass to an action or to Locator.in; undefined when it returned anything else.
frameFrameRefThe frame the expression ran in.
isVisibleboolean
boundsRect

FrameInfo

interface

FrameInfo describes a single frame within a page's frame tree, as Page.frames and CloudBrowser.pages report it.

To act in a frame, hand its id to frameById: css("button.pay").in(frameById(f.frameId)). walkFrames visits a frame and everything below it.

Fields
frameIdstring
urlstring
namestringThe frame's name (its iframe's name attribute), empty when it has none. What frameName goes by.
isOOPIFboolean
hasJSContextboolean
isLoadingboolean
isVisibleboolean
absoluteRectRect
relativeRectRect
childrenFrameInfo[]

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

Fields
ref?LocatorNames the element, ready to pass to an action or to Locator.in, and frame is the frame it lives in.
frameFrameRef
backendNodeIdnumberbackendNodeId and frameId are the same element as the DOM mirror addresses it (DomMirror.getNode, DomMirror.reveal, Page.highlightNode).
frameIdstring
tagNamestring
textContentstring
isVisibleboolean
boundsRect

InterceptedResponse describes a network response captured by a response wait condition or CloudBrowser.waitForAnyResponse.

Fields
urlstring
statusCodenumber
headersHeader[]
bodystring

OccluderInfo

interface

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

Fields
ref?LocatorNames the blocker itself: pass it to Page.click to click it, or to Locator.in to look for its close button inside it. Undefined when it could not be named.
frameIdstringThe frame the blocker lives in, which may differ from the target's (a page-level modal covering an iframe).
tagNamestring
idstring
classNamestring
textstring
boundsRect
pointerEventsstringComputed pointer-events keyword (e.g. "auto", "none", "all"). Lets you tell an invisible pass-through layer from one that genuinely swallows the click.
visibilitystringComputed visibility keyword ("visible", "hidden", "collapse").
opacitynumberComputed opacity (0..1). 0 means visually invisible but it may still intercept clicks depending on pointerEvents.
zIndexstringComputed effective z-index as a string ("0" when auto / not stacked).
hittableWhileInvisiblebooleanTrue 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.
positionstringComputed 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

interface

PageInfo describes an open page (tab or popup) inside a browser context, as CloudBrowser.pages found it.

Fields
pagePageThe handle to act on the page.
browserContextIdstring
urlstring
titlestring
viewportRect
frameTreeFrameInfo
isFocusedbooleanWhether this is the page that has the focus; exactly one page has it. See CloudBrowser.focusedPage.
isPopupbooleanWhether the page is a popup window (window.open with window features) rather than a tab.
opener?PageThe page that opened this one, if it is still open. Also set for rel=noopener, since the page still came from it.
openerFrameId?stringThe frame that opened this page, which may be a frame of opener other than its main frame.

ReactionInfo

interface

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

Fields
reactionIdstringStable id assigned by Page.addReaction (pass to removeReaction).
matchSelectorstringSet if the reaction matches by CSS selector.
matchJsExpressionstringSet if the reaction matches by JS expression.
actionSelectorstringSet if the click target differs from the matched element.
actionJsExpressionstringSet if the click target differs from the matched element.
matchLocatorThe 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 String(r.match) to see where the reaction looks.
visiblebooleanWhether the match additionally requires the element to be visible.
allPagesbooleanWhether the reaction was registered for every page (CloudBrowser.addReaction) rather than for one.

ReadCanvasResult 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 format is "rgba". originClean reports whether the canvas was untainted (informational — the read succeeds either way).

Fields
successboolean
ref?LocatorNames the canvas that was read, and frame the frame it was found in; as in ElementResult.
frameFrameRef
dataBase64string
widthnumber
heightnumber
originCleanboolean

RentResponse

interface

RentResponse is the result of renting a browser via the REST API.

Fields
sessionIdstring
grpcUrlstring
countryCodestring
timezonestring
acceptLanguagestring
fingerprintstring

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

Fields
dataBase64string
widthnumber
heightnumber

How a run ended.

Fields
successbooleanFalse when the script failed to compile or threw; result then holds the message.
resultstringThe return value as JSON, or the error message.
stoppedbooleanTrue when the run was cancelled, or the session went away under it, rather than the script returning on its own.

ScriptResult

interface

The outcome of a blocking Page.runScript.

Fields
successbooleanFalse when the script failed to compile or threw; result then holds the message.
resultstringThe return value as JSON, or "undefined" when the script returned nothing. On failure it is the error message.
runIdstringNames 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.
logScriptLogEntry[]Everything the script printed, in order.
truncatedbooleanTrue when the script printed more than the reply holds, in which case log is the tail of the output rather than all of it.

One run still in flight, as Page.listScriptRuns reports it.

Fields
runIdstring
runningMsnumberHow long the run has been going, in milliseconds.

SelectOptionResult reports which option a selectByXxx call ended up selecting.

Fields
selectedIndexnumber
selectedValuestring
selectedTextstring
ref?LocatorNames the <select>, and frame the frame it was found in; as in ElementResult.
frameFrameRef

StreamAnswer

interface

StreamAnswer is what CloudBrowser.startStream replies with.

Fields
answerSdpstringSDP answer to apply as your peer's remote description.
viewport{ width: number; height: number } | nullThe page's viewport in CSS pixels — the coordinate space its input expects. The video may be displayed at any size, so map your pointer positions into this space before sending them. It comes back with the answer rather than from a separate CloudBrowser.pages so it cannot race the stream or describe a different page, and the browser pushes {"type":"viewport","width":W,"height":H} on the reliable "input" data channel whenever it changes. Null against an older engine.

A captcha condition matched. Solve it with Page.solveCaptcha.

Fields
kind"captcha"
captchaWaitCaptcha

A css or js condition matched.

Fields
kind"element"
elementWaitElement

A request condition matched.

Fields
kind"request"
requestInterceptedRequest

A response condition matched.

Fields
kind"response"
responseInterceptedResponse

WaitResult

type alias
type WaitResult = | WaitElementResult | WaitCaptchaResult | WaitRequestResult | WaitResponseResult

WaitResult is the outcome of a Page.wait / Page.waitAny call: which condition matched (index, in argument order), what kind it was, and what it matched. Narrow on kind to reach the payload:

const r = await page.waitAny(css("#done"), response("*\/api/token*")); if (r.kind === "response") console.log(r.response.body);

A timeout does not resolve: it throws WaitError.

Data types

49 types

Everything else the API passes around: handles, events, records and enums.

AuthSession

interface

AuthSession is a portable snapshot of a context's signed-in Google account and/or DBSC sessions. Every field is optional, so a context that only has DBSC sessions (no primary account) or only a sign-in (no DBSC) round-trips.

Pair it with getCookies()/setCookies() and getStorage()/setStorage() to move a whole persona between fresh contexts.

Fields
gaiaId?stringGaia obfuscated account id.
email?stringAccount email.
refreshToken?stringOAuth refresh token (persistent).
wrappedBindingKey?stringBase64 of the wrapped device-binding key for the refresh token. Absent means the token is unbound.
signinScopedDeviceId?stringSignin-scoped device id; must travel with the token.
syncConsent?booleanTrue if the account should be restored at Sync consent.
dbscSessions?DbscSession[]Device Bound Session Credentials for this context (all bound sites).

Button

type alias
type Button = "left" | "right" | "middle"

Mouse button used by Page.click.

A captcha was found on page. See ContextEvent.

Fields
kind"captchaDetected"
pagePage
solveIdstringIdentifies the solve in captchaResolved and in the captchas of the actions it held.
frameIdstringThe frame the challenge was found in.
captchaKindstringThe type of challenge, a short stable name such as "turnstile".
trigger"auto" | "command"What found it: "auto" (auto-solve) or "command" (Page.solveCaptcha).
state"solving" | "waiting_for_focus" | "skipped""solving": the solve starts now. "waiting_for_focus": the page does not have the focus and auto-solve waits for it (see CaptchaAutoSolveOpts.unfocused). "skipped": the page reached CaptchaAutoSolveOpts.maxSolvesPerMinute; captchaResolved follows at once with code "limit_reached".
interruptedCommand?stringThe action running on the page when the captcha appeared ("click", "fill", "type", "drag"), held until the solve ends.

A captcha solve that held an action while it ran. Listed under captchas in the action's result.

Fields
solveIdstringThe solve's id, as in the captchaDetected / captchaResolved events.
successbooleanWhether the challenge was solved.
durationMsnumberHow long the action was held, in milliseconds.
outcome"resumed" | "restarted" | "continued" | "failed"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").

The solve announced by captchaDetected ended. See ContextEvent.

Fields
kind"captchaResolved"
pagePage
solveIdstring
successbooleanWhether the challenge was solved.
durationMsnumberFrom detection to the end, in milliseconds, including any wait for the focus.
attemptsnumberInteraction rounds the solve needed; 0 if it never got to interact.
interruptedCommand?stringAs in captchaDetected.
interruptedOutcome?CaptchaInterruption["outcome"]What interruptedCommand does now; see CaptchaInterruption.outcome.
error?{ code: string; message: string }Present 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).

ClickAction

type alias
type ClickAction = "click" | "press" | "release"

Mouse phase performed by Page.click.

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

Fields
userAgentstring
acceptLanguagestring
platformstring
platformVersionstring
architecturestring
bitnessstring
modelstring
mobileboolean
wow64boolean
brandsUaBrand[]
fullVersionListUaBrand[]
proxyProxyConfig
cookies?CookieParam[]Set when getClientIdentity was called with withCookies: true.
storage?StorageOriginEntry[]Set when getClientIdentity was called with withStorage: true.

ContextEvent

type alias
type ContextEvent = | { kind: "snapshot"

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.

- snapshot: every page of the browser. It replaces whatever you hold. The first event is always one; another comes only if this listener fell so far behind that events had to be dropped. - pageOpened: a tab or popup one of the pages opened, or one a call created. A page that takes the focus as it opens is followed by a pageFocused. - pageClosed: focusedPage has the focus now. A pageFocused follows if the focus moved. - pageFocused: page has the focus now. - pageUpdated: page committed a navigation or set a title. - captchaDetected: a captcha was found on page, by auto-solve (CloudBrowser.enableCaptchaAutoSolve) or by Page.solveCaptcha. Exactly one captchaResolved with the same solveId follows. - captchaResolved: that solve ended. - reactionFired: a reaction (Page.addReaction, CloudBrowser.addReaction) matched on page and clicked, or tried to. A reaction registered for every page reports once per page it fires on.

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.

type ContextEventHandler = (event: ContextEvent) => void

Called once per context event.

Calls are sequential and in the order the browser reported the changes. A handler that keeps the reader busy for long makes the server drop this listener's backlog and start over with a snapshot.

Partition metadata for partitioned cookies (CHIPS).

Fields
topLevelSitestring
hasCrossSiteAncestorboolean

DbscSession

interface

DbscSession is one Device Bound Session Credentials entry.

Fields
sitestringSerialized schemeful site key, e.g. "https://google.com".
sessionstringBase64 of the serialized DBSC Session proto. It includes the wrapped binding key, which is portable under WRC's software key provider.
type DomChangeHandler = (mirror: DomMirror) => void

Called after the tree changed. root is a fresh object whenever anything below it changed, so it can be compared by identity and rendered with memoized components.

DomNode

interface

A node in the mirrored page, in CDP's DOM.Node shape — the same shape Page.getDOM returns, with two additions that 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 DomNode.children, present once the element has been expanded, and nothing about walking the tree has to know a process boundary runs through it.

Fields
nodeIdnumber
backendNodeIdnumber
nodeTypenumber
nodeNamestring
localName?string
nodeValue?string
attributes?string[]Flat name, value, name, value, ..., as CDP sends it.
childNodeCount?numberTotal children in the page, whether or not they are in children. An <iframe> reports 1: the document it hosts.
children?DomNode[]Present once the node has been expanded.
shadowRoots?DomNode[]Author shadow roots, when the mirror was started with pierce.
frameIdstringThe 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?stringFor 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.
type DomResyncHandler = (reason: DomResyncReason) => void

Called when the mirror had to be rebuilt, after the new tree is in place.

type DomResyncReason = | "documentReplaced" | "overflow" | "rendererGone" | "slowReader" | string

Why a mirror had to be rebuilt.

DomSnapshot

interface

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.

Fields
rootstring
frameIdstring
seqnumberThe page sequence this snapshot is the baseline for.

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

Fields
ref?LocatorNames the element, ready to pass to an action such as Page.click. Undefined when it could not be named.
tagNamestringUpper-case tag name, e.g. "INPUT", "BUTTON", "DIV".
id?stringid attribute, if present.
name?stringname attribute, if present.
className?stringclass attribute, if present.
inputType?string<input> type, if the element is an <input>.
text?stringWhitespace-collapsed textContent/value snippet (max 120 chars).
editablebooleanWhether this element is itself an editable text sink (input / textarea / contenteditable).

FrameRef

interface

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

Fields
idstringThe frame's id, usable with frameById. It stays the same across navigations of the frame.
urlstringThe URL of the document the frame showed when the element was found.
mainbooleanWhether it is the page's main frame.

HeaderModification is one entry passed to CloudBrowser.modifyRequest. Write it as a plain object literal.

Fields
actionHeaderModificationAction"add" inserts a new header, "edit" replaces an existing header's value, "remove" drops the header.
namestringHeader name the action applies to.
value?stringHeader value for add/edit; ignored for remove.
before?stringPositions an "add" immediately before the named existing header; otherwise the header is appended at the end. Ignored for edit/remove.
after?stringPositions an "add" immediately after the named existing header. Mirror of before; ignored for edit/remove.
type HeaderModificationAction = "add" | "edit" | "remove"

Action verb for a HeaderModification.

IceServer

interface

IceServer is one entry for a WebRTC RTCPeerConnection's iceServers config: a TURN (or STUN) URL plus the short-lived credentials to authenticate with it. Pass these to your peer before creating the offer.

Fields
urlsstring[]ICE server URLs (e.g. turn:relay.example.com:3478?transport=udp).
usernamestringShort-lived TURN REST username (empty for plain STUN).
credentialstringShort-lived TURN REST credential (empty for plain STUN).

InterceptedRequest describes an outgoing request captured by a request wait condition or CloudBrowser.waitForAnyRequest.

Fields
methodstring
urlstring
headersHeader[]
bodystring
resourceTypestring

NetworkBodies

type alias
type NetworkBodies = "none" | "text" | "all"

Which response bodies a network capture keeps. Kept bodies are not part of the exchange; read them with CloudBrowser.readNetworkBody.

NetworkBody

interface

A whole captured body, from CloudBrowser.readNetworkBody.

Fields
dataUint8Array
truncatedbooleanThe kept body is shorter than the original; see the exchange's flag.

One range of a captured body, from CloudBrowser.readNetworkBodyRange.

Fields
dataUint8ArrayThe bytes read; empty past the end of the body.
totalSizenumberBytes kept for the body as a whole.
truncatedbooleanMatches the exchange's truncated flag for this body.

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

Fields
requestIdstringUnique per hop.
chainIdstringShared by every hop of one redirect chain.
redirectIndexnumber0 for the original request, incremented once per redirect followed.
frameIdstringThe frame that issued the request; empty for worker traffic.
isOopifbooleanWhether that frame runs in its own process. Capture happens in the browser process, so cross-process iframes are included.
resourceTypeNetworkResourceType
methodstring
urlstring
initiatorUrlstringThe origin that started the request; empty when the browser itself did.
requestHeadersHeader[]
requestHeadersAreWirebooleanWhether 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.
requestBodyIdstringNames the request body; read it with CloudBrowser.readNetworkBody. Empty when the request had no body. Bodies never travel with the exchange.
requestBodySizenumberBytes kept for the request body.
requestBodyTruncatedbooleanPart 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.
hasResponsebooleanFalse when the request failed before any response arrived; see error.
statusCodenumber
statusTextstring
mimeTypestring
protocolstringNegotiated ALPN protocol, e.g. "h2" or "http/1.1".
remoteAddressstring
servedFromNetworkServedFrom
responseHeadersHeader[]
responseHeadersAreWireboolean
responseBodyIdstringNames the response body; read it with CloudBrowser.readNetworkBody. Empty when body capture did not apply to this exchange — see NetworkCaptureOptions.bodies.
responseBodySizenumberBytes kept for the response body, after content decoding.
responseBodyTruncatedbooleanThe kept body is shorter than the one the page received: it hit the per-body cap or the load ended early.
encodedDataLengthnumberBytes on the wire, not body size; 0 for a response served from cache.
errorstringNet error name (e.g. "net::ERR_ABORTED"), empty on success.
type NetworkExchangeHandler = (exchange: NetworkExchange) => void

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.

Blocking here stalls the capture: awaiting something slow means the server keeps buffering, and once its per-reader bound is reached it drops the oldest entries, which NetworkCapture.dropped reports. Hand slow work (uploads, IndexedDB) to a queue of your own instead of awaiting it here.

type NetworkResourceType = | "document" | "subframe" | "script" | "stylesheet" | "image" | "font" | "media" | "fetch" | "worker" | "manifest" | "object" | "csp-report" | "other" | (string & {})

NetworkResourceType is the kind of load an exchange belongs to.

Typed as a union with a string fallback so an exchange from a newer browser still carries its value through instead of failing to type. Note that fetch(), XMLHttpRequest and EventSource all report "fetch": they are indistinguishable at the capture point.

type NetworkServedFrom = | "network" | "cache" | "serviceWorker" | "wrcStaticCache" | "wrcSynthetic" | (string & {})

NetworkServedFrom says where an exchange's response came from. "wrcStaticCache" is browserscale's own static cache — see CloudBrowser.setStaticPaths.

ProxyConfig

interface

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

Fields
schemestring
hoststring
portnumber
usernamestring
passwordstring
masquestring

ProxyScheme

type alias
type ProxyScheme = "http" | "socks5"

The protocol the browser speaks to its proxy. "http" (CONNECT) is the default. A SOCKS5 proxy always resolves host names itself, so "socks5" covers what is elsewhere called socks5h.

A reaction clicked on page, or tried to. See ContextEvent.

Fields
kind"reactionFired"
pagePage
reactionIdstringThe id Page.addReaction or CloudBrowser.addReaction returned.
frameIdstringThe frame the match was found in.
successbooleanWhether the click was carried out.
interruptedCommand?stringThe action running on the page when the reaction acted ("fill", "type", "drag", ...), which waited until the click was done.
error?{ code: string; message: string }Present 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

interface

Rect describes a position and size in CSS pixels.

Fields
xnumber
ynumber
widthnumber
heightnumber

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
abort?booleanDefault false.

ScriptEvent

interface

One item on a session's script event stream. Exactly one of log and finished is set.

Fields
runIdstringThe run that produced this event.
log?ScriptLogEntryA console line the script printed.
finished?ScriptFinishedThe end of the run. No further event for that run follows.
type ScriptEventHandler = (event: ScriptEvent) => void

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.

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 a queue of your own instead of awaiting it here.

One console.* call from a script.

Fields
levelstring"info", "warning" or "error", from console.log / .warn / .error.
messagestringThe logged arguments, already stringified the way console does it.
timestampDateWhen the script printed the line, stamped in the browser.

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.

Fields
indexnumber0-based position among the selector's matches in document order.
countnumberHow many elements the selector matched.

SessionUsage

interface

SessionUsage 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 resolves with the final figures, so there is no need to read it right before stopping.

Fields
wallTimenumberReal time since the session's browser was created, in seconds.
cpuTimenumberUser plus kernel CPU time in seconds. Only time a thread actually ran on a core counts; waiting and idling do not.
minMemorynumberThe least memory the session held once its browser was ready, in bytes. Sampled about once a second.
averageMemorynumberThe 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.
peakMemorynumberThe most memory held at any one moment, in bytes.
renderersUsednumberRenderer processes that hosted at least one of the session's frames: one per site its pages and cross-site iframes needed.
framesCreatednumberChild frames created in the session's pages, whether or not they got a process of their own.
bytesReceivednumberBytes the session's pages, workers and service workers received over the network: 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.
bytesSentnumberBytes they sent the same way: HTTP requests with headers and bodies, and WebSocket messages.

StorageItem

interface

StorageItem is a single localStorage key/value pair.

Fields
keystring
valuestring

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
itemsStorageItem[]

UaBrand

interface

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

Fields
brandstring
versionstring

WaitCaptcha

interface

The challenge a captcha wait condition matched.

Fields
kindstringThe type of challenge, a short stable name such as "turnstile".
frameFrameRefThe frame the challenge was found in.

WaitCondition

type alias
type WaitCondition = Locator | CaptchaCondition | RequestCondition | ResponseCondition

Anything Page.wait/Page.waitAny accepts: an element Locator (css / js), captcha, request or response.

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

Fields
indexnumberIndex into the condition list this entry describes.
statestringLast 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?LocatorNames the element last seen for this condition; undefined if it was never found or the match was not an element.
frameIdstringframeId where it was last seen (empty if never found).
scopeError?stringSet 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.
isVisiblebooleanWhether it was CSS-visible at the last observation.
bounds?RectLast known rect in root-viewport coordinates (undefined if never found).
occluder?OccluderInfoThe intercepting element, present iff state === "found_occluded".
selectorMatch?SelectorMatchSet when the selector matched several elements and this status is about one other than the first, or none of them is rendered.

WaitElement

interface

The element a css or js wait condition matched.

Fields
ref?LocatorNames 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. Undefined when a js() expression matched with a truthy value that is not an element. See ref for how long it stays good.
frameFrameRefThe frame the element lives in (for a non-element match, the frame the expression ran in).
isVisiblebooleanWhether the element was visible at the match.
boundsRectThe element's rect in root-viewport CSS pixels.
selectorMatch?SelectorMatchSet when a css condition matched an element other than the selector's first match.

WaitKind

type alias
type WaitKind = WaitResult["kind"]

The kind of a WaitResult.

WaitUntil

type alias
type WaitUntil = "load" | "domcontentloaded" | "networkidle"

Lifecycle event Page.navigate waits for before returning.