TypeScript SDK Reference
browserscale-ts. All methods return a Promise; the return types below show the resolved value (the Promise<…> wrapping is implicit).CloudBrowser
38 methodsCloudBrowser 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 CloudBrowseraddReaction(match: Locator, opts: ReactionOpts | undefined): stringRegisters 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.
| match | Locator | the css()/js() locator to watch for |
| opts | ReactionOpts | undefined | optional reaction customization; see ReactionOpts |
// Accept the consent banner on whichever page it shows up.
const id = await browser.addReaction(css("button#accept"));stringthe reactionId (pass to CloudBrowser.removeReaction)| BrowserScaleError | `match` (or `opts.on`) is not a css()/js() locator, or a server/transport error |
captureNetwork
method on CloudBrowsercaptureNetwork(opts: NetworkCaptureOptions, onExchange: NetworkExchangeHandler): NetworkCaptureStarts 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.
| opts | NetworkCaptureOptions | which requests to capture and whether to keep bodies |
| onExchange | NetworkExchangeHandler | called 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();
}NetworkCaptureNetworkCapture handle for stopping the capture and inspecting how it endedclearCookies
method on CloudBrowserclearCookies(): voidDeletes 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();voidclearStorage
method on CloudBrowserclearStorage(origin: string | undefined): voidDeletes localStorage in the browser context.
| origin | string | undefined | if 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();voidcontextEvents
method on CloudBrowsercontextEvents(onEvent: ContextEventHandler): ContextEventsRegisters 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.
| onEvent | ContextEventHandler | called 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();ContextEventsContextEvents handle for stopping the listener and inspecting how it endedcreatePage
method on CloudBrowsercreatePage(): PageOpens 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");| CommandError | create_failed - the browser could not open the page, typically capacity |
disableCaptchaAutoSolve
method on CloudBrowserdisableCaptchaAutoSolve(): booleanStops CloudBrowser.enableCaptchaAutoSolve. A solve already running finishes; one waiting for the focus is resolved with code "disabled".
await browser.disableCaptchaAutoSolve();booleanwhether auto-solve was enabledenableCaptchaAutoSolve
method on CloudBrowserenableCaptchaAutoSolve(opts: CaptchaAutoSolveOpts | undefined): voidMakes 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.
| opts | CaptchaAutoSolveOpts | undefined | settings; 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)`);void| BrowserScaleError | an `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 CloudBrowserfocusedPage(): PageReturns 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");| NoPageError | the browser has no page yet; createPage opens the first |
getApiKey
method on CloudBrowsergetApiKey(): stringReturns the API key used to rent this session.
stringgetAuthSession
method on CloudBrowsergetAuthSession(): AuthSession | undefinedExports 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));AuthSession | undefinedAuthSession, or undefined when there is nothing to exportgetClientIdentity
method on CloudBrowsergetClientIdentity(opts: ClientIdentityOptions): ClientIdentityReturns 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.
| opts | ClientIdentityOptions | optionally fold in cookies / storage |
const id = await browser.getClientIdentity({ withCookies: true });
console.log(id.userAgent, id.proxy.host, id.cookies?.length);ClientIdentitythe session's ClientIdentitygetCookies
method on CloudBrowsergetCookies(): 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);CookieParam[]CookieParam[], one per cookie in the contextgetFingerprint
method on CloudBrowsergetFingerprint(): stringReturns the browser fingerprint id in use for this session.
stringgetPage
method on CloudBrowsergetPage(pageId: string): PageReturns the Page with this id. It makes no call and does not check the id: a page that is gone shows on the Page's first call.
| pageId | string | a page id, as reported by pages or an error |
const page = browser.getPage(savedPageId);
await page.navigate("https://example.com");getSessionId
method on CloudBrowsergetSessionId(): stringReturns the unique server-assigned id for this browser session.
stringgetStorage
method on CloudBrowsergetStorage(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.
| origin | string | undefined | if 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);
}StorageOriginEntry[]StorageOriginEntry[], one per origin with localStorage datagetStreamConfig
method on CloudBrowsergetStreamConfig(): 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 });IceServer[]the ICE servers for the client RTCPeerConnectiongetUsage
method on CloudBrowsergetUsage(): SessionUsageReports 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`);SessionUsageSessionUsage as of nowlistReactions
method on CloudBrowserlistReactions(): 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);ReactionInfo[]the reactions registered for every pagemodifyRequest
method on CloudBrowsermodifyRequest(urlPattern: string, opts: {
body?: string;
modifications?: HeaderModification[];
timeoutMs?: number;
} | undefined): InterceptedRequest | nullWaits 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.
| urlPattern | string | URL wildcard to wait for |
| opts | { body?: string; modifications?: HeaderModification[]; timeoutMs?: number; } | undefined | optional 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);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 reportedpages
method on CloudBrowserpages(): 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;PageInfo[]PageInfo[] for every page currently open in the contextreadNetworkBody
method on CloudBrowserreadNetworkBody(bodyId: string): NetworkBodyReads a whole captured body: an exchange's requestBodyId or responseBodyId.
Bodies are stored by the browser, not sent with the exchange, so reading one is a separate call. They stay readable after the capture stops, until the session ends.
The body is fetched in ranges and assembled in memory. For very large bodies, use CloudBrowser.readNetworkBodyRange to process them piece by piece.
| bodyId | string | requestBodyId or responseBodyId from a NetworkExchange |
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)),
);
},
);NetworkBodythe body and whether the kept body is shorter than the originalreadNetworkBodyRange(bodyId: string, offset: number | undefined, length: number | undefined): NetworkBodyRangeReads 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.
| bodyId | string | requestBodyId or responseBodyId from a NetworkExchange |
| offset | number | undefined | first byte to read (default 0) |
| length | number | undefined | bytes to read (default and maximum 2 MiB) |
NetworkBodyRangeNetworkBodyRange with the bytes and the body's total sizeremoveReaction
method on CloudBrowserremoveReaction(reactionId: string): booleanRemoves 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.
| reactionId | string | id returned by CloudBrowser.addReaction or Page.addReaction |
const removed = await browser.removeReaction(id);booleantrue if a pending reaction with this id existed and was removedsetAuthSession
method on CloudBrowsersetAuthSession(session: AuthSession): voidImports 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.
| session | AuthSession | session as returned by getAuthSession() |
await browser.setAuthSession(saved);
await page.navigate("https://mail.google.com");voidsetBlockList
method on CloudBrowsersetBlockList(patterns: string[]): voidReplaces 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.
| patterns | string[] | URL wildcards to block; empty array clears the list |
await browser.setBlockList([
"*.doubleclick.net/*",
"*googletagmanager.com*",
]);voidsetCookies
method on CloudBrowsersetCookies(cookies: CookieParam[]): voidWrites 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.
| cookies | CookieParam[] | cookies to write; empty array is a no-op |
await browser.setCookies([
{ name: "auth", value: "tok", domain: "example.com", path: "/" },
]);voidsetProxy
method on CloudBrowsersetProxy(proxyHost: string, proxyPort: number, proxyUsername: string, proxyPassword: string, options: ProxyOptions): voidChanges the runtime proxy for this session.
Takes effect for new requests immediately; in-flight requests keep their original routing. Pass an empty proxyHost to clear the proxy and route directly.
| proxyHost | string | upstream proxy host; empty disables the proxy |
| proxyPort | number | upstream proxy port; ignored when proxyHost is empty |
| proxyUsername | string | proxy auth user; empty for unauthenticated proxies |
| proxyPassword | string | proxy auth password; empty for unauthenticated proxies |
| options | ProxyOptions | the 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" });voidsetStaticPaths
method on CloudBrowsersetStaticPaths(blobName: string, patterns: string[]): voidConfigures 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.
| blobName | string | server-side identifier of the snapshot to serve from |
| patterns | string[] | URL wildcards to redirect to the cache; empty disables |
await browser.setStaticPaths("snap-2026-05", ["*.example.com/*"]);voidsetStorage
method on CloudBrowsersetStorage(storage: StorageOriginEntry[]): voidWrites localStorage entries into the browser context, grouped by origin.
Accepts the same structure getStorage() returns, so a dump can be fed back verbatim. Existing keys are overwritten. Works without any open page; pages that are already open will not observe the writes until they reload.
| storage | StorageOriginEntry[] | entries to write, grouped by origin |
await browser.setStorage([
{
origin: "https://example.com",
items: [
{ key: "token", value: "abc123" },
{ key: "theme", value: "dark" },
],
},
]);voidstartNetworkCapture
method on CloudBrowserstartNetworkCapture(opts: NetworkCaptureOptions): voidArms 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.
| opts | NetworkCaptureOptions | which requests to capture and whether to keep bodies |
voidstartStream
method on CloudBrowserstartStream(offerSdp: string): StreamAnswerAnswers 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.
| offerSdp | string | your RTCPeerConnection's SDP offer |
const { answerSdp, viewport } = await browser.startStream(offer.sdp);
await pc.setRemoteDescription({ type: "answer", sdp: answerSdp });StreamAnswerthe SDP answer to apply as the remote description, plus the viewport to map input coordinates into| NoPageError | the browser has no page to show yet; createPage opens the first |
stopNetworkCapture
method on CloudBrowserstopNetworkCapture(): booleanDisarms the session's capture.
booleanwhether a capture was runningstopStream
method on CloudBrowserstopStream(): voidTears 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();voidstreamNetworkExchanges
method on CloudBrowserstreamNetworkExchanges(onExchange: NetworkExchangeHandler): NetworkCaptureSubscribes to the session's capture without arming one, for reading a capture that CloudBrowser.startNetworkCapture armed elsewhere. Several readers can watch the same capture, each with its own buffer.
Stopping the returned view detaches this reader and leaves the capture running, since other readers may still be attached.
| onExchange | NetworkExchangeHandler | called per exchange; see NetworkExchangeHandler for the ordering and blocking rules |
NetworkCaptureNetworkCapture attached to whatever capture is running; onExchange simply never fires when none iswaitForAnyRequest
method on CloudBrowserwaitForAnyRequest(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.
| patterns | RequestPattern[] | one or more URL patterns (with optional abort flags) |
| opts | { timeoutMs?: number } | undefined | optional 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);{ 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)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.
| patterns | RequestPattern[] | one or more URL patterns (with optional abort flags) |
| opts | { timeoutMs?: number } | undefined | optional timeoutMs; omit to use the server default |
const { index, response } = await browser.waitForAnyResponse(
[{ url: "*\/api/login" }],
{ timeoutMs: 5000 },
);
console.log(index, response?.statusCode);{ index: number; response: InterceptedResponse | null }object with index (matched pattern index) and response (the captured status/headers/body; null if no body was returned)Locator
6 methodsLocator says what a call is about: an element, and where on the page to look for it. It is used as a wait condition (passed to Page.wait/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.
| selector | string = "" | |
| jsExpression | string = "" | |
| refValue | string = "" | @internal The reference this locator stands for; read it with Locator.refString. |
| frameUrlPattern | string = "" | @internal A frame, named directly. These only work as a container. |
| frameNameValue? | string | @internal |
| frameIdValue | string = "" | @internal |
| isMainFrame | boolean = false | @internal |
| isAnyFrame | boolean = false | @internal |
| mustBeFrame | boolean = 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. |
| seenIn | string = "" | @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 Locatorin(container: Locator): LocatorSays 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.
| container | Locator | where 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!));Locatora new Locator for the same element, confined to the containerrefString
method on LocatorrefString(): stringReturns 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));stringthe reference as text, or ""steady
method on Locatorsteady(ms: number): LocatorRequires 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.
| ms | number | steady-state duration in milliseconds; 0 disables |
await page.wait(css(".banner").steady(0));Locatora new Locator with the override appliedtoJSON
method on LocatortoJSON(): stringWrites 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.
stringtoString
method on LocatortoString(): stringDescribes the locator for logs and error messages: what it names and what it is looked for in, outermost last.
stringvisible
method on Locatorvisible(v: boolean): LocatorEnforces 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.
| v | boolean | true to require visibility, false to skip the check |
await page.wait(css("#hidden").visible(false));Locatora new Locator with the override appliedBrowserConfig
5 methodsConfiguration for renting a browser session. Create with the required parameters, then chain optional setters.
| apiKey | string | |
| rentDuration | number | |
| proxyHost | string | |
| proxyPort | number | |
| proxyUsername | string | |
| proxyPassword | string |
withCountryCode
method on BrowserConfigwithCountryCode(countryCode: string): BrowserConfigSets the geo-IP country code for the rented session.
Drives both the assigned exit-IP region and the locale defaults (Accept-Language, timezone fallback) when those are not overridden separately.
| countryCode | string | ISO-3166 country code (e.g. "DE", "US") |
new BrowserConfig(apiKey, 600, "", 0, "", "").withCountryCode("DE");BrowserConfigthis BrowserConfig for chainingwithFingerprint
method on BrowserConfigwithFingerprint(fingerprint: string): BrowserConfigPins a specific browser fingerprint id for the session.
When omitted the server picks a fingerprint based on the country code. Pass a known id (e.g. one returned by a previous rental) to keep fingerprints stable across sessions.
| fingerprint | string | server-side fingerprint id |
new BrowserConfig(apiKey, 600, "", 0, "", "").withFingerprint("fp_abc123");BrowserConfigthis BrowserConfig for chainingwithMasque
method on BrowserConfigwithMasque(hostPort: string): BrowserConfigRoutes 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.
| hostPort | string | the MASQUE proxy as "host:port" |
new BrowserConfig(apiKey, 600, "proxy.example.com", 8080, "user", "pass").withMasque("masque.example.com:443");BrowserConfigthis BrowserConfig for chainingwithProxyScheme
method on BrowserConfigwithProxyScheme(scheme: ProxyScheme): BrowserConfigSets the protocol of the proxy passed to the constructor. Without it the proxy is an HTTP proxy.
| scheme | ProxyScheme | "http" or "socks5" |
new BrowserConfig(apiKey, 600, "proxy.example.com", 1080, "user", "pass").withProxyScheme("socks5");BrowserConfigthis BrowserConfig for chainingwithTimezone
method on BrowserConfigwithTimezone(timezone: string): BrowserConfigSets the IANA timezone for the rented session.
| timezone | string | IANA timezone (e.g. "Europe/Berlin") |
new BrowserConfig(apiKey, 600, "", 0, "", "").withTimezone("Europe/Berlin");BrowserConfigthis BrowserConfig for chainingCaptchaCondition
1 methodCaptchaCondition 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 CaptchaConditionin(container: Locator): CaptchaConditionConfines the captcha condition to a container, the way Locator.in does for an element: only a challenge inside that frame or element counts. Without it, a challenge anywhere on the page does.
| container | Locator | where to look |
// Only a challenge in the checkout frame, not the one in the chat widget.
const checkout = frameUrl("*checkout.example.com/*");
await page.wait(captcha().in(checkout));CaptchaConditiona new CaptchaCondition confined to the containerContextEvents
2 methodsA 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 ContextEventsstop(): voidEnds 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.
voidwait
method on ContextEventswait(): voidResolves once the listener ends — ContextEvents.stop, a dead session or a transport failure.
voidDomMirror
9 methodsA 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 DomMirrorcollapse(node: DomNode): voidStops 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.
| node | DomNode |
voidexpand
method on DomMirrorexpand(node: DomNode, depth: number | undefined): voidFetches 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.
| node | DomNode | |
| depth | number | undefined | levels below the node, default 1 |
voidgetNode
method on DomMirrorgetNode(frameId: string, backendNodeId: number): DomNode | undefinedLooks up a node by its address.
| frameId | string | |
| backendNodeId | number |
DomNode | undefinedisExpanded
method on DomMirrorisExpanded(node: DomNode): booleanWhether this node's children are known. Changes inside a node that is not expanded arrive only as an updated childNodeCount.
| node | DomNode |
booleanlocator
method on DomMirrorlocator(node: DomNode): LocatorTurns a mirror node into a reference that Page.click, Page.fill and every other call with a target takes: the way to act on a node picked in the tree. See Page.nodeRef, which this calls with the node's address.
| node | DomNode | a node of this mirror |
const button = await mirror.locator(node);
await page.click(button);LocatorLocator naming the node, usable as a target or a containerresync
method on DomMirrorresync(reason: DomResyncReason): voidThrows 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.
| reason | DomResyncReason |
voidreveal
method on DomMirrorreveal(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.
| backendNodeId | number | |
| frameId | string | undefined |
DomNode[]the ancestor chain, the main document first, or an empty array if the node is not on the pagestop
method on DomMirrorstop(): voidStops mirroring and detaches the reader. Idempotent, safe in a finally.
voidwait
method on DomMirrorwait(): voidResolves once the mirror ends — stop(), a dead session, a transport failure.
voidNetworkCapture
2 methodsNetworkCapture is a running capture, returned by CloudBrowser.captureNetwork. Exchanges are delivered to the handler passed there; this handle only exists to stop the capture and to report how it went.
stop
method on NetworkCapturestop(): voidEnds 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.
voidwait
method on NetworkCapturewait(): voidResolves 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.
voidPage
48 methodsPage is one page (tab or popup) of the browser. Everything that acts on a document — navigating, waiting, clicking, typing, reading — is a Page method.
A Page is only the page's id: it holds no state and asks for none, so it never goes stale on its own. Which pages exist and which has the focus is the browser's to know. When the page closes, its next call 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.
| id | string | The page's id, stable for the life of the page. |
| browser | CloudBrowser | The browser the page belongs to. |
addReaction
method on PageaddReaction(match: Locator, opts: ReactionOpts | undefined): stringRegisters 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.
| match | Locator | the css()/js() locator to watch for |
| opts | ReactionOpts | undefined | optional 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"),
});stringthe reactionId (pass to Page.removeReaction)| BrowserScaleError | `match` (or `opts.on`) is not a css()/js() locator, or a server/transport error |
click
method on Pageclick(target: Locator, opts: ClickOpts | undefined): ElementResultTriggers 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.
| target | Locator | locator describing what to click; at is also valid |
| opts | ClickOpts | undefined | optional 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 });ElementResultElementResult with success, the element's ref and frame, post-scroll isVisible, element bounds, and the root-viewport (rootX, rootY) where the click landed| BrowserScaleError | invalid locator, or a server/transport error (element not found, frame not found, timeout, page closed) |
| ClickError | the 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 |
| StaleRefError | the 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 Pageclose(): PageCloses 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();Pagethe page that has the focus afterwards; when the closed page had it, the browser hands it on, usually to the page that opened itdragBy
method on PagedragBy(target: Locator, offsetX: number, offsetY: number): DragResultPicks 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.
| target | Locator | locator describing the element to pick up |
| offsetX | number | horizontal distance to drag, in CSS pixels |
| offsetY | number | vertical distance to drag, in CSS pixels |
await page.dragBy(css(".slider .handle"), 120, 0);DragResultDragResult with the element's ref and frame and the final cursor position (rootX, rootY) where the drop happened| BrowserScaleError | invalid locator or a server/transport error |
| DragError | the 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 |
| StaleRefError | the 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 PagedragTo(target: Locator, absoluteX: number, absoluteY: number): DragResultPicks 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.
| target | Locator | locator describing the element to pick up |
| absoluteX | number | horizontal drop coordinate in the root viewport |
| absoluteY | number | vertical drop coordinate in the root viewport |
await page.dragTo(css(".card"), 800, 400);DragResultDragResult with the element's ref and frame and the final cursor position (rootX, rootY) where the drop happened| BrowserScaleError | invalid locator or a server/transport error |
| DragError | the 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 |
| StaleRefError | the 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 Pageevaluate(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".
| expression | string | JavaScript expression evaluated in the main frame |
| opts | EvaluateOpts | undefined | where 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;
}EvaluateResult<T>EvaluateResult with either value (non-Element) or element metadata (Element)| CommandError | code `"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(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.
| container | Locator | where the expression runs; see Locator.in |
| expression | string |
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");| StaleRefError | the container is a reference whose element is gone |
fill
method on Pagefill(target: Locator, text: string, opts: FillOpts | undefined): ElementResultClicks 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.
| target | Locator | locator describing the input element |
| text | string | text to type into the element |
| opts | FillOpts | undefined | optional 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 });ElementResultElementResult with success, the element's ref and frame and the root-viewport (rootX, rootY) where the element was clicked| BrowserScaleError | invalid locator, or a server/transport error (element not found, frame not found, timeout, page closed) |
| FillError | the 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 |
| StaleRefError | the 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 Pagefocus(): voidBrings 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();void| PageClosedError | the page has closed |
followScript
method on PagefollowScript(runId: string, onEvent: ScriptEventHandler): ScriptFollowWatches 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.
| runId | string | run to follow, or "" to follow every run on the page |
| onEvent | ScriptEventHandler | called 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();
}ScriptFollowScriptFollow handle for stopping the subscriptionframes
method on Pageframes(): FrameInfoReturns 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);
});FrameInfothe FrameInfo of the main frame, with its children| PageClosedError | the page has closed |
getDOM
method on PagegetDOM(frameId: string, opts: GetDOMOpts | undefined): DOMResultReturns 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.
| frameId | string | id of the frame to dump; empty string targets the main frame |
| opts | GetDOMOpts | undefined | optional depth: -1 full tree (default), 0 root only, N root + N descendant levels |
const { dom } = await page.getDOM();DOMResultDOMResult with the JSON string in .dom (the .hash field is populated by getDOMHash, not by this call)getDomChildren
method on PagegetDomChildren(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.
| backendNodeId | number | |
| frameId | string | |
| depth | number | undefined |
{ children: string; seq: number }getDOMHash
method on PagegetDOMHash(frameId: string): stringReturns 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.
| frameId | string | id of the frame to hash; empty string targets the main frame |
const hash = await page.getDOMHash();
if (hash !== lastHash) {
// DOM changed → re-fetch
}string16-char hex string (the first 8 bytes of sha256 of the DOM JSON)getDomRevision
method on PagegetDomRevision(frameId: string): numberA 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.
| frameId | string |
numbergetObservation
method on PagegetObservation(opts: GetObservationOpts | undefined): stringReturns 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.
| opts | GetObservationOpts | undefined | optional 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/*") });stringthe observation in the requested format, ready to hand to a model| StaleRefError | the scope is a reference whose element is gone |
getSelection
method on PagegetSelection(): stringReturns 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);stringthe selected text, or "" when nothing is selectedhighlight
method on Pagehighlight(target: Locator | null): voidPaints 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.
| target | Locator | null | the 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!);void| StaleRefError | the reference's element is gone |
highlightNode
method on PagehighlightNode(backendNodeId: number, frameId: string): voidPaints 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.
| backendNodeId | number | id of the node to highlight, or <= 0 to clear |
| frameId | string | id of the frame the node lives in; empty string targets the main frame |
await page.highlightNode(node.backendNodeId, node.frameId);voidinsertText
method on PageinsertText(text: string): voidPastes 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.
| text | string | the text to insert at the caret |
await page.insertText("hello world");voidinspectAtPosition
method on PageinspectAtPosition(x: number, y: number): InspectResultHit-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.
| x | number | viewport-relative x in CSS pixels |
| y | number | viewport-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 pointInspectResultInspectResult with the element's ref and frame, its address in the DOM mirror (backendNodeId, frameId), tag name, trimmed textContent, visibility and boundslistReactions
method on PagelistReactions(): 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));ReactionInfo[]the pending reactions for the pagelistScriptRuns
method on PagelistScriptRuns(): 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);
}ScriptRunInfo[]one entry per run still executingloadHTML
method on PageloadHTML(url: string, html: string, opts: LoadHTMLOpts | undefined): voidNavigates 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.
| url | string | the URL the page will show the html under |
| html | string | response body to serve |
| opts | LoadHTMLOpts | undefined | optional headers and statusCode (default 200) |
await page.loadHTML("https://example.com", "<h1>hi</h1>");
await page.wait(css("h1"));voidmirrorDom
method on PagemirrorDom(opts: DomMirrorOptions, onChange: DomChangeHandler, onResync: DomResyncHandler | undefined): DomMirrorStarts 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(); ``
| opts | DomMirrorOptions | initial depth and whether to pierce shadow roots |
| onChange | DomChangeHandler | called after every change, including the first snapshot |
| onResync | DomResyncHandler | undefined | called 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. |
moveTo
method on PagemoveTo(target: Locator): ElementResultMoves 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).
| target | Locator | locator describing where to move; at is also valid |
await page.moveTo(css("nav .menu"));ElementResultElementResult with the element's ref and frame, post-scroll isVisible, element bounds and the root-viewport (rootX, rootY) where the cursor ended up| BrowserScaleError | invalid locator or a server/transport error |
| MoveError | the target could not be located (`.code` is `"not_found"`, or `"container_not_found"` / `"outside_scope"` as in click); `.result` carries the resolved payload |
| StaleRefError | the target or a container is a reference whose element is gone (the call's own error, code `"stale_ref"`, is its `cause`) |
nodeRef
method on PagenodeRef(backendNodeId: number, frameId: string): LocatorTurns 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.
| backendNodeId | number | the node's DomNode.backendNodeId |
| frameId | string | the node's DomNode.frameId; empty is the main frame |
const button = await page.nodeRef(node.backendNodeId, node.frameId);
await page.click(button);LocatorLocator naming the node, usable as a target or a containerpressKey
method on PagepressKey(key: string, opts: { code?: string; modifiers?: number; location?: number } | undefined): voidFires 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.
| key | string | DOM KeyboardEvent.key value (e.g. "Enter", "a", "ArrowLeft") |
| opts | { code?: string; modifiers?: number; location?: number } | undefined | optional 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 });voidreadCanvas
method on PagereadCanvas(target: Locator, opts: ReadCanvasOpts | undefined): ReadCanvasResultReads 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.
| target | Locator | locator for the <canvas>; css, js or a reference |
| opts | ReadCanvasOpts | undefined | optional 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,
});ReadCanvasResultReadCanvasResult with the base64 image in dataBase64, the canvas width/height, the canvas's ref and frame and the originClean flag| StaleRefError | the target or a container is a reference whose element is gone |
releaseDomSubtree
method on PagereleaseDomSubtree(backendNodeId: number, frameId: string): voidStops reporting changes inside a node, and inside any frame below it. DomMirror.collapse calls this.
| backendNodeId | number | |
| frameId | string |
voidreleaseKey(key: string, opts: { code?: string; modifiers?: number; location?: number } | undefined): voidFires a single key-up event.
Mirror of pressKey. Same parameter semantics; use this to close a press cycle that was started with pressKey.
| key | string | |
| opts | { code?: string; modifiers?: number; location?: number } | undefined |
await page.pressKey("Shift", { code: "ShiftLeft", location: 1 });
await page.releaseKey("Shift", { code: "ShiftLeft", location: 1 });voidremoveReaction
method on PageremoveReaction(reactionId: string): booleanRemoves 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.
| reactionId | string | id returned by Page.addReaction |
const removed = await page.removeReaction(id);booleantrue if a pending reaction with this id existed and was removedrevealDomNode
method on PagerevealDomNode(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.
| backendNodeId | number | |
| frameId | string |
{ path: string; seq: number }runScript
method on PagerunScript(source: string): ScriptResultRuns 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.
| source | string | JavaScript 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);ScriptResultthe return value and the script's whole console output. A script that threw is reported as success: false, not as a rejectionscreenshot
method on Pagescreenshot(opts: ScreenshotOpts | undefined): ScreenshotResultCaptures 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.
| opts | ScreenshotOpts | undefined | optional 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"));ScreenshotResultScreenshotResult with the base64 image in dataBase64 and the physical pixel width/heightscrollTo
method on PagescrollTo(target: Locator): ElementResultScrolls the given element into view.
Whatever scroll container is closest to the element does the scrolling — nested scroll containers and out-of-process iframe chains are walked automatically. at is not a valid target here; scrolling needs a real element.
| target | Locator | locator describing the element to bring into view; at is rejected |
await page.scrollTo(css("#footer"));ElementResultElementResult with the element's ref and frame, post-scroll isVisible and the element's bounds after the scroll| BrowserScaleError | invalid locator or a server/transport error |
| ScrollError | the target could not be located/scrolled (`.code` is `"not_found"`, or `"container_not_found"` / `"outside_scope"` as in click); `.result` carries the resolved payload |
| StaleRefError | the 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 PageselectByIndex(target: Locator, index: number, opts: SelectOpts | undefined): SelectOptionResultPicks 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.
| target | Locator | locator describing the <select> element |
| index | number | zero-based option index |
| opts | SelectOpts | undefined | optional 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 });SelectOptionResultSelectOptionResult with the resolved selectedIndex, selectedValue and selectedText after the change| BrowserScaleError | invalid locator, or a server/transport error (frame not found, timeout, page closed) |
| SelectOptionError | the option could not be selected; `.code` is `"not_found"` (no `<select>`), `"option_not_found"`, or `"container_not_found"` / `"outside_scope"` as in click |
| StaleRefError | the target or a container is a reference whose element is gone (the call's own error, code `"stale_ref"`, is its `cause`) |
selectByText(target: Locator, text: string, opts: SelectOpts | undefined): SelectOptionResultPicks 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.
| target | Locator | locator describing the <select> element |
| text | string | the visible option text to match |
| opts | SelectOpts | undefined | optional select customization; see SelectOpts |
await page.selectByText(css("select#country"), "Germany");SelectOptionResultSelectOptionResult with the resolved selectedIndex, selectedValue and selectedText after the change| BrowserScaleError | invalid locator, or a server/transport error (frame not found, timeout, page closed) |
| SelectOptionError | the option could not be selected; `.code` is `"not_found"` (no `<select>`), `"option_not_found"`, or `"container_not_found"` / `"outside_scope"` as in click |
| StaleRefError | the target or a container is a reference whose element is gone (the call's own error, code `"stale_ref"`, is its `cause`) |
selectByValue(target: Locator, value: string, opts: SelectOpts | undefined): SelectOptionResultPicks 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.
| target | Locator | locator describing the <select> element |
| value | string | the value attribute to match |
| opts | SelectOpts | undefined | optional select customization; see SelectOpts |
await page.selectByValue(css("select#country"), "DE");SelectOptionResultSelectOptionResult with the resolved selectedIndex, selectedValue and selectedText after the change| BrowserScaleError | invalid locator, or a server/transport error (frame not found, timeout, page closed) |
| SelectOptionError | the option could not be selected; `.code` is `"not_found"` (no `<select>`), `"option_not_found"`, or `"container_not_found"` / `"outside_scope"` as in click |
| StaleRefError | the 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 PagesolveCaptcha(opts: { timeoutMs?: number; retryAmount?: number } | undefined): stringDetects 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.
| opts | { timeoutMs?: number; retryAmount?: number } | undefined | optional 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;
}stringempty string on success — the solution is applied for you| SolveCaptchaError | the challenge was not solved, with a `code` and, when one was found, its `kind`: |
startDomMirror
method on PagestartDomMirror(opts: DomMirrorOptions): DomSnapshotStarts (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.
| opts | DomMirrorOptions |
startScript
method on PagestartScript(source: string, onEvent: ScriptEventHandler): ScriptRunLaunches 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.
| source | string | JavaScript to execute |
| onEvent | ScriptEventHandler | called 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();ScriptRunScriptRun handle for awaiting or cancelling the runstopDomMirror
method on PagestopDomMirror(): voidStops the page's mirror, every frame of it. Idempotent.
voidstopScripts
method on PagestopScripts(runId: string): numberCancels 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.
| runId | string | run to cancel, or "" for all of them |
await page.stopScripts(""); // abandon everything runningnumberhow many runs were cancelled; 0 when the id named nothing in flighttype
method on Pagetype(text: string, opts: { clearFirst?: boolean } | undefined): voidTypes 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.
| text | string | the text to type as real key events |
| opts | { clearFirst?: boolean } | undefined | optional: 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");voidwait(condition: WaitCondition, opts: WaitOpts | undefined): WaitResultBlocks 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.
| condition | WaitCondition | the single condition to wait for |
| opts | WaitOpts | undefined |
const r = await page.wait(css(".success"));
console.log(r.element.bounds);waitAny
method on PagewaitAny(conditions: WaitCondition[], opts: WaitOpts | undefined): WaitResultBlocks 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.
| conditions | WaitCondition[] | one or more conditions to wait for; must be non-empty |
| opts | WaitOpts | undefined | optional 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);WaitResultWaitResult for the first matching condition| BrowserScaleError | a condition was invalid, or a server/transport error occurred |
| WaitError | no 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 |
RequestCondition
1 methodRequestCondition is the wait condition built by request. It is accepted by Page.wait/Page.waitAny only.
| urlPattern | string, | |
| abortFlag | boolean = false, |
abort
method on RequestConditionabort(v: boolean): RequestConditionDrops the matching request: it is not sent, and the page receives an empty 200 instead. The request is still returned in the wait result.
| v | boolean | true (the default) to drop the request, false to only observe it |
await page.wait(request("https://tracker.example.com/*").abort());RequestConditiona new RequestCondition with the flag appliedResponseCondition
1 methodResponseCondition is the wait condition built by response. It is accepted by Page.wait/Page.waitAny only.
| urlPattern | string, | |
| abortFlag | boolean = false, |
abort
method on ResponseConditionabort(v: boolean): ResponseConditionHides the matching response from the page: it receives an empty 200 instead. The real response is still returned in the wait result.
| v | boolean | true (the default) to hide the response, false to pass it through |
await page.wait(response("https://example.com/api/token*").abort());ResponseConditiona new ResponseCondition with the flag appliedScriptFollow
2 methodsScriptFollow is a read-only view of script output, returned by Page.followScript.
stop
method on ScriptFollowstop(): voidEnds the subscription. Idempotent, and safe to call from a finally. It never cancels a run: other readers, and the script itself, are unaffected.
voidwait
method on ScriptFollowwait(): voidResolves once the subscription ends — ScriptFollow.stop, a dead session or a transport failure.
voidScriptRun
3 methodsScriptRun is a script running in the background, returned by Page.startScript. Its output is delivered to the handler passed there; this handle exists to await the outcome and to cancel the run.
detach
method on ScriptRundetach(): voidStops 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.
voidstop
method on ScriptRunstop(): voidCancels 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.
voidwait
method on ScriptRunwait(): ScriptFinishedResolves 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.
ScriptFinishedhow the script endedWebSocketTransport
1 methodstream
method on WebSocketTransportstream(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.
| method | DescMethodStreaming<I, O> | |
| signal | AbortSignal | undefined | |
| _timeoutMs | number | undefined | |
| _header | HeadersInit | undefined | |
| input | AsyncIterable<MessageInitShape<I>> | |
| _contextValues | ContextValues | undefined |
StreamResponse<I, O>Functions
21 functionsPackage-level functions: renting, listing, connecting to and stopping sessions, and the locator constructors.
anyFrame
functionanyFrame(): LocatoranyFrame names every frame, one after the other: the main document, then each iframe. It is what makes a js locator search all frames, which it does not do by itself. Put in a frame container with in(), it means that frame and the frames below it.
await page.wait(
js(`[...document.querySelectorAll('button')].find(b => b.innerText === 'Accept all')`)
.in(anyFrame()),
);LocatorLocator usable only as a containerat
functionat(x: number, y: number): Locatorat targets viewport coordinates instead of an element.
Useful for clicking inside a canvas, hovering decorative regions, or dispatching events at synthetic positions. Action-only — using it in wait() throws at send time. Note that only click and moveTo accept at; scrollTo, drag, fill and select all require a real element.
| x | number | viewport-relative x in CSS pixels |
| y | number | viewport-relative y in CSS pixels |
// Click at canvas-relative coordinates.
await page.click(at(120, 240));LocatorLocator usable only as an action targetcaptcha
functioncaptcha(): CaptchaConditioncaptcha matches as soon as a supported captcha or bot-protection challenge is on the page and waits for an answer. A widget that passed, or passes without interaction, does not count.
It is a state, like css: a challenge that is already showing matches at once. On a match the result's kind is "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();CaptchaConditionCaptchaCondition usable only as a wait conditionconnectSession
functionconnectSession(grpcUrl: string, apiKey: string, sessionId: string): CloudBrowserAttaches 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.
| grpcUrl | string | session host gRPC URL from the original rent (grpc:// or grpcs://) |
| apiKey | string | API key the session was rented with |
| sessionId | string | id of the existing session |
const browser = connectSession(grpcUrl, apiKey, sessionId);
try {
await page.navigate("https://example.com");
} finally {
await browser.stopBrowser();
}CloudBrowserCloudBrowser attached to the existing sessioncreateWebSocketBrowser
functioncreateWebSocketBrowser(wsUrl: string, sessionId: string, apiKey: string, fingerprint: string): CloudBrowserAttaches 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.
| wsUrl | string | WebSocket URL (ws:// or wss://) of the session host |
| sessionId | string | id of the existing session |
| apiKey | string | API key authorizing access to the session |
| fingerprint | string | browser fingerprint id; empty if unknown |
const browser = createWebSocketBrowser(
"wss://session-abc.browserscale.example.com/ws",
sessionId,
apiKey,
);
await page.navigate("https://example.com");CloudBrowserCloudBrowser attached to the existing sessioncss
functioncss(selector: string): Locatorcss waits for / targets an element matching the given CSS selector.
Without Locator.in the selector is looked for on the whole page: the main document first, then every frame in the order they appear, frames nobody can see last. The result says which frame it was found in, so a button inside a consent or payment iframe needs no frame named. Use in() to confine the search to one frame, one dialog or one component.
Where the element has to be visible (a wait condition or reaction, and every action), the selector means its first rendered match: matches that are not rendered at all (display:none, visibility:hidden, no size) are passed over, so a hidden copy such as the one in a closed mobile menu does not shadow the visible element. A covered or offscreen match is still rendered and stays the target. When a later match was taken, the result says which one in selectorMatch. With .visible(false) a wait or reaction takes the first match.
When used in Page.wait/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.
| selector | string | CSS 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);LocatorLocator usable as a wait condition, an action target or a containerframe
functionframe(container: Locator): Locatorframe requires the element a locator names to be an iframe.
A container made with css, js or a reference is entered as a frame when the element is an iframe and searched as a subtree when it is anything else, which is usually what is wanted. Wrap it in frame() to hear about it when the page gave something else: the call then fails with code "container_not_found", saying the element is not a frame, instead of quietly searching a subtree.
| container | Locator | a css(), js() or reference locator |
const pay = frame(css("iframe.pay"));
await page.fill(css("input[name=cardnumber]").in(pay), card);LocatorLocator usable as a containerframeById
functionframeById(frameId: string): LocatorframeById names one frame by its id, as a result's frame.id or Page.frames report it. The id stays the same across navigations of the frame, but belongs to this session: prefer frameUrl, frameName or the iframe's own selector in anything that is written down.
| frameId | string | the frame's id |
const found = await page.wait(css("#card"));
const title = await page.evaluateIn(frameById(found.element.frame.id), "document.title");LocatorLocator usable only as a containerframeName
functionframeName(name: string): LocatorframeName names a frame by its name: window.name, which starts out as the iframe's name attribute. Otherwise as frameUrl.
| name | string | the frame's name |
await page.fill(css("input[name=q]").in(frameName("search")), "shoes");LocatorLocator usable only as a containerframeUrl
functionframeUrl(pattern: string): LocatorframeUrl names a frame by the URL of the document it shows.
It is a container: pass it to Locator.in, Page.evaluateIn or 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.
| pattern | string | URL 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));LocatorLocator usable only as a containerjs
functionjs(expression: string): Locatorjs waits for / targets the result of a JavaScript expression.
Without Locator.in the expression runs in the page's main document, and only there. With in() it runs in the document the container leads to; when the container is an element rather than a frame, the expression gets that element as __wrc.scope and has to return an element inside it.
Same wait defaults as css (visible, 500ms steady); these only apply when the expression returns a DOM Element. For non-Element truthy values (boolean, string, number, plain object) both fields are no-ops and the condition matches as soon as the value is truthy. Use .visible(false) / .steady(0) to opt out.
| expression | string | JavaScript 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),
);LocatorLocator usable as a wait condition, an action target or a containerlistBrowsers
functionlistBrowsers(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.
| apiKey | string | API 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);BrowserInfo[]the running sessions, oldest first; empty when the key holds nonemainFrame
functionmainFrame(): LocatormainFrame names the page's main document. A css locator put in it is not looked for in any iframe.
// Only the page's own button, not one in an embedded widget.
await page.click(css("button.accept").in(mainFrame()));LocatorLocator usable only as a containerref
functionref(value: string): Locatorref targets the very element an earlier call found, by its reference.
Every result that names an element carries its reference as a ready Locator (WaitElement.ref, ElementResult.ref, OccluderInfo.ref, …), so this constructor is only needed for a reference that arrived as text: an observation prints one per frame (# ref @<document>), and a row's number followed by that suffix is the element's reference.
A reference names its element and the document it lives in, so no frame is named with it and Locator.in does not apply. It stays good while the element is in its document. Once a navigation replaced the document, or the element was removed, a call given it rejects with a StaleRefError instead of acting on whatever took its place.
| value | string | the 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"));LocatorLocator usable as an action target or a containerrentBrowser
functionrentBrowser(config: BrowserConfig): CloudBrowserRents 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.
| config | BrowserConfig | rental parameters |
const cfg = new BrowserConfig("sk_…", 600, "", 0, "", "");
const browser = await rentBrowser(cfg);
try {
await page.navigate("https://example.com");
} finally {
await browser.stopBrowser();
}CloudBrowserCloudBrowser ready to drive the rented sessionrequest
functionrequest(urlPattern: string): RequestConditionrequest matches the first request whose URL matches urlPattern.
Unlike css or captcha, a request is an event, not a state: only a request issued after the wait started counts. Start the wait before the action that triggers the request, 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.
| urlPattern | string | URL 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);RequestConditionRequestCondition usable only as a wait conditionresponse
functionresponse(urlPattern: string): ResponseConditionresponse matches the response to the first request whose URL matches urlPattern, once it has fully arrived.
Same event semantics and scope as request: only a request issued after the wait started counts, so start the wait before the action. On a match the result's kind is "response" and response carries the status, headers and body.
| urlPattern | string | URL 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);ResponseConditionResponseCondition usable only as a wait conditionsetApiEndpoint
functionsetApiEndpoint(endpoint: string): voidOverrides the HTTP rent/stop endpoint.
Defaults to https://api.browserscale.cloud. Call this before any rentBrowser / stopBrowser call if you need to point at a private browserscale deployment.
| endpoint | string | base URL of the rent/stop service, with no trailing slash |
setApiEndpoint("https://browserscale.internal.example.com");voidstopBrowser
functionstopBrowser(apiKey: string, sessionId: string): SessionUsage | undefinedReleases a session without needing a CloudBrowser handle.
Useful when a session id was persisted across processes and the rental outlived the original handle. Only calls the rent stop endpoint; there is no gRPC connection to close in this form.
| apiKey | string | API key the session was rented with |
| sessionId | string | id of the session to release |
const usage = await stopBrowser(apiKey, sessionId);SessionUsage | undefinedSessionUsage what the session consumed over its whole life; undefined when the server could not report itthrowCommandError
functionthrowCommandError(command: string, error: { code: string; message: string } | undefined): voidRaises 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.
| command | string | |
| error | { code: string; message: string } | undefined |
voidwalkFrames
functionwalkFrames(frame: FrameInfo, fn: (frame: FrameInfo, depth: number)): voidCalls 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.
| frame | FrameInfo | where 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);
});voidErrors
13 errorsThrown by the command they belong to, each with a stable code and typed detail. Catch them with instanceof.
BrowserScaleError
classBrowserScaleError 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
classClickError 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).
| code | string | Machine-stable failure code, e.g. "occluded_no_reachable_point" (target fully covered, no exposed part reachable), "occluded_after_evade" (a reposition was tried but the target was still covered), "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? | OccluderInfo | The intercepting element (present for occlusion codes). |
| evadeAttempted | boolean | Whether a pointer reposition was tried before giving up. |
| focusedPageId? | string | For code "page_not_focused", the page that has the focus. The call throws a PageNotFocusedError around this error then. |
| result? | ElementResult | Resolved element + coordinates at the failed action. Present when this is the thrown top-level error; undefined when nested inside another error. |
DragError
classDragError 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".
| code | string | |
| clickError? | ClickError | |
| result | DragResult | Resolved source + coordinates at the failed drag (success is false). |
FillError
classFillError 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.
| code | string | Machine-stable failure code (see the class doc for the full set). |
| clickError? | ClickError | The underlying click-core failure that prevented focusing/typing. Present for the click-phase codes; undefined for "focus_stolen"/"focus_lost". |
| focusedBackendNodeId? | number | Node that held focus when fill gave up (0 if nothing was focused), for the "focus_stolen"/"focus_lost" codes. |
| focusedElement? | FocusedElement | The element that grabbed focus instead of the target ("focus_stolen"), so you can act on it (e.g. a consent button). |
| targetEditable? | boolean | The fill target's own state at the point of failure (the focus codes): whether it is still an editable text sink and its current text length. |
| targetValueLength? | number | |
| result | ElementResult | Resolved element + coordinates at the failed action (success is false). |
MoveError
classMoveError 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.
| code | string | "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? | string | For code "page_not_focused", the page that has the focus. The call throws a PageNotFocusedError around this error then. |
| result | ElementResult |
NoPageError
classNoPageError 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
classPageClosedError 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; }
| pageId | string | The id of the page that closed. |
| focusedPage | Page | The page that has the focus now. |
PageNotFocusedError
classPageNotFocusedError 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 }
| focusedPage | Page | The page that has the focus. |
ScrollError
classScrollError is thrown by Page.scrollTo when the target could not be located/scrolled.
| code | string | "not_found", or one of the codes about where the target was looked for: "container_not_found", "outside_scope", "stale_ref". |
| result | ElementResult |
SelectOptionError
classSelectOptionError 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.
| code | string | "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". |
| result | SelectOptionResult |
SolveCaptchaError
classSolveCaptchaError is thrown by Page.solveCaptcha when the challenge was not solved.
| code | string | "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). |
| kind | string | The type of challenge found, a short stable name such as "turnstile"; empty when none was. |
| solveId | string | The solve's id in the captchaDetected / captchaResolved events; empty when no solve ran. |
StaleRefError
classStaleRefError 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")); }
| ref? | Locator | The reference that went stale: the call's target, or the container it was to be looked for in. |
| url | string | Where the frame the element was seen in is now, or the page's URL when that frame is gone too. When it differs from the URL the element was found at, the frame navigated; when it is the same, the document was reloaded or the element removed. Empty if it could not be read. |
WaitError
classWaitError 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.
| code | string | Machine-stable failure code, currently always "timeout". |
| conditions | WaitConditionStatus[] | Per-condition status, same order/length as the conditions passed to wait. |
Options
17 typesOptional settings a command accepts.
CaptchaAutoSolveOpts
interfaceSettings for CloudBrowser.enableCaptchaAutoSolve. Omitted fields use the server defaults.
| solveTimeoutMs? | number | Budget for one solve, in milliseconds. Default 60000. |
| retryAmount? | number | Per-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? | number | At 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
interfaceOptional customization for Page.click. All fields are optional; missing or zero values mean "use the server default".
| button? | Button | Mouse button. Default "left". |
| clickCount? | number | 1 = 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. |
ClientIdentityOptions
interfaceOptions for CloudBrowser.getClientIdentity.
| withCookies? | boolean | Also return the session's cookies in ClientIdentity.cookies. |
| withStorage? | boolean | Also return the session's localStorage in ClientIdentity.storage. |
| storageOrigin? | string | With withStorage, restrict to this origin (e.g. "https://example.com"). Omit to get all origins. |
CookieParam
interfaceCookieParam is one entry returned by getCookies() or passed to setCookies().
| name | string | |
| value | string | |
| url? | string | |
| domain | string | |
| path | string | |
| secure? | boolean | |
| httpOnly? | boolean | |
| sameSite? | string | |
| expires? | number | |
| priority? | string | |
| sourceScheme? | string | |
| sourcePort? | number | |
| partitionKey? | CookiePartitionKey |
EvaluateOpts
interfaceOptional customization for Page.evaluate.
| in? | Locator | Where 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? | number | How 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? | boolean | true 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
interfaceOptional customization for Page.fill. All fields are optional; missing values mean "use the server default".
| clearFirst? | boolean | true wipes the field's existing content with Ctrl+A, Delete before typing. Default (false) appends to whatever is already in the field. |
| timeoutMs? | number | Budget 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? | number | Settle window in ms before the focus click, mirroring the click steady-time. Omit for the server default (750). 0 skips settling. |
GetDOMOpts
interfaceDepth used by getDOM(). 0 = whole tree (default), >0 = limited depth.
| depth? | number |
GetObservationOpts
interfaceOptional customization for Page.getObservation.
| 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? | number | Cap on emitted elements per frame. Default 800 — a safety net against runaway documents; maxTotalTokens is the limit that normally binds. |
| maxTextLength? | number | Cap 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? | number | Budget 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? | boolean | Include 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? | boolean | Only emit elements intersecting the frame's current viewport. |
| scope? | Locator | Observes 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
interfaceOptional customization for Page.loadHTML.
| headers? | { name: string; value: string }[] | Extra headers to attach to the synthetic response. |
| statusCode? | number | Default 200. |
NetworkCaptureOptions
interfaceConfigures CloudBrowser.captureNetwork.
There is deliberately no byte-cap option: kept bodies are stored on a machine shared with other sessions, so the server owns the quota. When a session's bodies exceed it, the oldest are dropped first.
| patterns? | string[] | 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? | NetworkBodies | Response-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
interfaceOptional parts of a proxy beyond host, port and credentials.
| scheme? | ProxyScheme | The proxy's protocol; "http" when omitted. |
| masque? | string | A MASQUE proxy ("host:port") that carries HTTP/3 with the proxy's credentials. See BrowserConfig.withMasque. |
ReactionOpts
interfaceOptional customization for Page.addReaction and CloudBrowser.addReaction. All fields are optional; missing or zero values mean "use the server default".
| on? | Locator | Override 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? | Button | Mouse button for the click. Default "left". |
| clickCount? | number | 1 = single click (default), 2 = double-click. |
| intervalMs? | number | Poll cadence in milliseconds for the shared page loop. Default 300. |
ReadCanvasOpts
interfaceOptional customization for Page.readCanvas.
| format? | "png" | "jpeg" | "webp" | "rgba" | Output encoding: "png" (default), "jpeg", "webp", or "rgba" for the raw unpremultiplied RGBA pixel buffer. |
| quality? | number | Encode quality 0-100 for "jpeg"/"webp" (ignored otherwise). Default 90. |
| sx? | number | Optional 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 |
ScreenshotOpts
interfaceOptional customization for Page.screenshot.
| format? | "png" | "jpeg" | "webp" | Image format: "png" (default), "jpeg", or "webp". |
| quality? | number | Encode quality 0-100 for "jpeg"/"webp" (ignored for "png"). Default 90. |
SelectOpts
interfaceOptional customization for Page.selectByIndex, Page.selectByValue and Page.selectByText.
| fireEvents? | boolean | false suppresses change/input events. Default (true) fires the standard events after the selection. |
WaitOpts
interfaceOptional customization for Page.wait / Page.waitAny.
| timeoutMs? | number | Omitted leaves it to the API, which defaults to 30 000 ms. |
Results
25 typesWhat commands hand back.
BrowserInfo
interfaceBrowserInfo describes one running session, as listBrowsers reports it.
| sessionId | string | |
| grpcUrl | string | The endpoint this session is driven from — the same one rent returned. It is what makes a listed id usable: pass it to connectSession. |
| startTime | number | Unix seconds the session was rented at. |
| rentDuration | number | The rental length in seconds; 0 means unlimited. |
| remainingSeconds? | number | Seconds left on the rental, and undefined for an unlimited one — there is nothing to count down. |
| countryCode | string | |
| timezone | string | |
| proxyHost | string | |
| publicIp | string | The address the session egresses from. |
| gpuIndex? | number | The physical card the session renders on, and undefined on a software-rendered host. |
DOMResult
interfaceDOMResult is the full-tree DOM snapshot returned by Page.getDOM, plus its sha256:8 hash for cheap change detection.
| hash | string | |
| dom | string |
DragResult
interfaceDragResult is the outcome of a Page.dragBy gesture: the resolved source element and the start/end coordinates of the performed drag.
| success | boolean | |
| ref? | Locator | Names the dragged element, and frame the frame it was found in; as in ElementResult. |
| frame | FrameRef | |
| startX | number | |
| startY | number | |
| endX | number | |
| endY | number | |
| captchas? | CaptchaInterruption[] | The captcha solves that held the drag, in order. Absent if none did. |
| selectorMatch? | SelectorMatch | Set when a css source resolved to other than the selector's first match. |
ElementResult
interfaceElementResult is the outcome of an element interaction such as Page.click, Page.fill or Page.scrollTo: the resolved element plus the root-relative coordinates the action was performed at.
| success | boolean | |
| ref? | Locator | Names the element the call acted on: pass it to a later action to act on exactly this element again, or to Locator.in to look inside it. Undefined for a call that was given coordinates (at). See ref for how long it stays good. |
| frame | FrameRef | The frame the element was found in. A css target is looked for on the whole page, so this is where to read which frame it was. |
| isVisible | boolean | |
| bounds | Rect | |
| rootX | number | |
| rootY | number | |
| 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? | SelectorMatch | Set when a css target resolved to other than the selector's first match. |
EvaluateResult
interfaceEvaluateResult 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.
| success | boolean | False 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". |
| value | T | |
| ref? | Locator | Names the element the expression returned, ready to pass to an action or to Locator.in; undefined when it returned anything else. |
| frame | FrameRef | The frame the expression ran in. |
| isVisible | boolean | |
| bounds | Rect |
FrameInfo
interfaceFrameInfo 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.
InspectResult
interfaceInspectResult describes the topmost element hit at viewport-relative (x, y). An undefined ref (and backendNodeId === 0) means nothing was found at that position.
| ref? | Locator | Names the element, ready to pass to an action or to Locator.in, and frame is the frame it lives in. |
| frame | FrameRef | |
| backendNodeId | number | backendNodeId and frameId are the same element as the DOM mirror addresses it (DomMirror.getNode, DomMirror.reveal, Page.highlightNode). |
| frameId | string | |
| tagName | string | |
| textContent | string | |
| isVisible | boolean | |
| bounds | Rect |
InterceptedResponse
interfaceInterceptedResponse describes a network response captured by a response wait condition or CloudBrowser.waitForAnyResponse.
| url | string | |
| statusCode | number | |
| headers | Header[] | |
| body | string |
OccluderInfo
interfaceOccluderInfo describes the element that intercepted a click — the element sitting on top of the target at the intended click point. Coordinates are in root-viewport CSS pixels. Populated on ClickError for occlusion failures so the caller can locate and clear the blocker (e.g. find its close button).
| ref? | Locator | Names 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. |
| frameId | string | The frame the blocker lives in, which may differ from the target's (a page-level modal covering an iframe). |
| tagName | string | |
| id | string | |
| className | string | |
| text | string | |
| bounds | Rect | |
| pointerEvents | string | Computed pointer-events keyword (e.g. "auto", "none", "all"). Lets you tell an invisible pass-through layer from one that genuinely swallows the click. |
| visibility | string | Computed visibility keyword ("visible", "hidden", "collapse"). |
| opacity | number | Computed opacity (0..1). 0 means visually invisible but it may still intercept clicks depending on pointerEvents. |
| zIndex | string | Computed effective z-index as a string ("0" when auto / not stacked). |
| hittableWhileInvisible | boolean | True when the blocker intercepts clicks even while invisible (computed pointer-events in {all, painted, fill, stroke}): a real click is swallowed even at visibility:hidden / opacity:0. When false and the element is invisible, a real click would fall through. |
| position | string | Computed position keyword. "fixed"/"sticky" means the blocker is pinned (by itself or an ancestor) and stays put no matter where the pointer goes — clear it by scrolling the target out from under it; ordinary overlays often collapse once the pointer leaves. |
PageInfo
interfacePageInfo describes an open page (tab or popup) inside a browser context, as CloudBrowser.pages found it.
| page | Page | The handle to act on the page. |
| browserContextId | string | |
| url | string | |
| title | string | |
| viewport | Rect | |
| frameTree | FrameInfo | |
| isFocused | boolean | Whether this is the page that has the focus; exactly one page has it. See CloudBrowser.focusedPage. |
| isPopup | boolean | Whether the page is a popup window (window.open with window features) rather than a tab. |
| opener? | Page | The page that opened this one, if it is still open. Also set for rel=noopener, since the page still came from it. |
| openerFrameId? | string | The frame that opened this page, which may be a frame of opener other than its main frame. |
ReactionInfo
interfaceReactionInfo describes a still-pending reaction, as returned by Page.listReactions and CloudBrowser.listReactions. One-shot reactions that have already fired are gone and never appear here.
| reactionId | string | Stable id assigned by Page.addReaction (pass to removeReaction). |
| matchSelector | string | Set if the reaction matches by CSS selector. |
| matchJsExpression | string | Set if the reaction matches by JS expression. |
| actionSelector | string | Set if the click target differs from the matched element. |
| actionJsExpression | string | Set if the click target differs from the matched element. |
| match | Locator | The locator the reaction watches for, as it was given to addReaction: the selector or expression above together with the container it was put in with Locator.in, and its visible setting. Print it with String(r.match) to see where the reaction looks. |
| visible | boolean | Whether the match additionally requires the element to be visible. |
| allPages | boolean | Whether the reaction was registered for every page (CloudBrowser.addReaction) rather than for one. |
ReadCanvasResult
interfaceReadCanvasResult 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).
RentResponse
interfaceRentResponse is the result of renting a browser via the REST API.
| sessionId | string | |
| grpcUrl | string | |
| countryCode | string | |
| timezone | string | |
| acceptLanguage | string | |
| fingerprint | string |
ScreenshotResult
interfaceScreenshotResult is a single captured image of the page, returned by Page.screenshot. dataBase64 holds the encoded image bytes (PNG by default); width and height are in physical pixels.
| dataBase64 | string | |
| width | number | |
| height | number |
ScriptFinished
interfaceHow a run ended.
| success | boolean | False when the script failed to compile or threw; result then holds the message. |
| result | string | The return value as JSON, or the error message. |
| stopped | boolean | True when the run was cancelled, or the session went away under it, rather than the script returning on its own. |
ScriptResult
interfaceThe outcome of a blocking Page.runScript.
| success | boolean | False when the script failed to compile or threw; result then holds the message. |
| result | string | The return value as JSON, or "undefined" when the script returned nothing. On failure it is the error message. |
| runId | string | Names the run. It arrives with the reply, so it is only useful after the fact — to match up log lines a separate follower already saw. |
| log | ScriptLogEntry[] | Everything the script printed, in order. |
| truncated | boolean | True when the script printed more than the reply holds, in which case log is the tail of the output rather than all of it. |
ScriptRunInfo
interfaceOne run still in flight, as Page.listScriptRuns reports it.
| runId | string | |
| runningMs | number | How long the run has been going, in milliseconds. |
SelectOptionResult
interfaceSelectOptionResult reports which option a selectByXxx call ended up selecting.
StreamAnswer
interfaceStreamAnswer is what CloudBrowser.startStream replies with.
| answerSdp | string | SDP answer to apply as your peer's remote description. |
| viewport | { width: number; height: number } | null | The 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. |
WaitCaptchaResult
interfaceA captcha condition matched. Solve it with Page.solveCaptcha.
| kind | "captcha" | |
| captcha | WaitCaptcha |
WaitElementResult
interfaceA css or js condition matched.
| kind | "element" | |
| element | WaitElement |
WaitRequestResult
interfaceA request condition matched.
| kind | "request" | |
| request | InterceptedRequest |
WaitResponseResult
interfaceA response condition matched.
| kind | "response" | |
| response | InterceptedResponse |
WaitResult
type aliastype WaitResult = | WaitElementResult | WaitCaptchaResult | WaitRequestResult | WaitResponseResultWaitResult 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 typesEverything else the API passes around: handles, events, records and enums.
AuthSession
interfaceAuthSession 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.
| gaiaId? | string | Gaia obfuscated account id. |
| email? | string | Account email. |
| refreshToken? | string | OAuth refresh token (persistent). |
| wrappedBindingKey? | string | Base64 of the wrapped device-binding key for the refresh token. Absent means the token is unbound. |
| signinScopedDeviceId? | string | Signin-scoped device id; must travel with the token. |
| syncConsent? | boolean | True if the account should be restored at Sync consent. |
| dbscSessions? | DbscSession[] | Device Bound Session Credentials for this context (all bound sites). |
Button
type aliastype Button = "left" | "right" | "middle"Mouse button used by Page.click.
CaptchaDetectedEvent
interfaceA captcha was found on page. See ContextEvent.
| kind | "captchaDetected" | |
| page | Page | |
| solveId | string | Identifies the solve in captchaResolved and in the captchas of the actions it held. |
| frameId | string | The frame the challenge was found in. |
| captchaKind | string | The 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? | string | The action running on the page when the captcha appeared ("click", "fill", "type", "drag"), held until the solve ends. |
CaptchaInterruption
interfaceA captcha solve that held an action while it ran. Listed under captchas in the action's result.
| solveId | string | The solve's id, as in the captchaDetected / captchaResolved events. |
| success | boolean | Whether the challenge was solved. |
| durationMs | number | How 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"). |
CaptchaResolvedEvent
interfaceThe solve announced by captchaDetected ended. See ContextEvent.
| kind | "captchaResolved" | |
| page | Page | |
| solveId | string | |
| success | boolean | Whether the challenge was solved. |
| durationMs | number | From detection to the end, in milliseconds, including any wait for the focus. |
| attempts | number | Interaction rounds the solve needed; 0 if it never got to interact. |
| interruptedCommand? | string | As 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 aliastype ClickAction = "click" | "press" | "release"Mouse phase performed by Page.click.
ClientIdentity
interfaceClientIdentity is everything the browser reports about itself on the wire, so an out-of-browser HTTP client can reproduce matching request headers: the User-Agent, the full UA client-hint set, the Accept-Language, and the session's proxy. cookies and storage are populated only when requested via withCookies / withStorage.
| userAgent | string | |
| acceptLanguage | string | |
| platform | string | |
| platformVersion | string | |
| architecture | string | |
| bitness | string | |
| model | string | |
| mobile | boolean | |
| wow64 | boolean | |
| brands | UaBrand[] | |
| fullVersionList | UaBrand[] | |
| proxy | ProxyConfig | |
| cookies? | CookieParam[] | Set when getClientIdentity was called with withCookies: true. |
| storage? | StorageOriginEntry[] | Set when getClientIdentity was called with withStorage: true. |
ContextEvent
type aliastype 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.
ContextEventHandler
type aliastype ContextEventHandler = (event: ContextEvent) => voidCalled 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.
CookiePartitionKey
interfacePartition metadata for partitioned cookies (CHIPS).
| topLevelSite | string | |
| hasCrossSiteAncestor | boolean |
DbscSession
interfaceDbscSession is one Device Bound Session Credentials entry.
| site | string | Serialized schemeful site key, e.g. "https://google.com". |
| session | string | Base64 of the serialized DBSC Session proto. It includes the wrapped binding key, which is portable under WRC's software key provider. |
DomChangeHandler
type aliastype DomChangeHandler = (mirror: DomMirror) => voidCalled 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
interfaceA 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.
| nodeId | number | |
| backendNodeId | number | |
| nodeType | number | |
| nodeName | string | |
| localName? | string | |
| nodeValue? | string | |
| attributes? | string[] | Flat name, value, name, value, ..., as CDP sends it. |
| childNodeCount? | number | Total 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. |
| frameId | string | The frame this node lives in. Always set. Together with backendNodeId this is the node's address: node ids are handed out per renderer and restart per frame, so two frames can and do use the same one, and the id on its own is ambiguous across a page. |
| contentFrameId? | string | For 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. |
DomResyncHandler
type aliastype DomResyncHandler = (reason: DomResyncReason) => voidCalled when the mirror had to be rebuilt, after the new tree is in place.
DomResyncReason
type aliastype DomResyncReason = | "documentReplaced" | "overflow" | "rendererGone" | "slowReader" | stringWhy a mirror had to be rebuilt.
DomSnapshot
interfaceThe opening snapshot: the main frame's document. Child frames are not in it — their documents are fetched by expanding the <iframe> elements that host them, which is also what starts mirroring them.
| root | string | |
| frameId | string | |
| seq | number | The page sequence this snapshot is the baseline for. |
FocusedElement
interfaceFocusedElement is a lightweight descriptor of an element — enough to identify it (and decide what to do) without another DOM round-trip. It names the element that stole focus in a FillError focus-loss failure.
| ref? | Locator | Names the element, ready to pass to an action such as Page.click. Undefined when it could not be named. |
| tagName | string | Upper-case tag name, e.g. "INPUT", "BUTTON", "DIV". |
| id? | string | id attribute, if present. |
| name? | string | name attribute, if present. |
| className? | string | class attribute, if present. |
| inputType? | string | <input> type, if the element is an <input>. |
| text? | string | Whitespace-collapsed textContent/value snippet (max 120 chars). |
| editable | boolean | Whether this element is itself an editable text sink (input / textarea / contenteditable). |
FrameRef
interfaceFrameRef is the frame an element was found in. Every result that names an element carries one, so a call that searched the whole page says where its element lives.
| id | string | The frame's id, usable with frameById. It stays the same across navigations of the frame. |
| url | string | The URL of the document the frame showed when the element was found. |
| main | boolean | Whether it is the page's main frame. |
Header
interfaceHeader is a single HTTP header (name/value pair) on an intercepted request or response.
| name | string | |
| value | string |
HeaderModification
interfaceHeaderModification is one entry passed to CloudBrowser.modifyRequest. Write it as a plain object literal.
| action | HeaderModificationAction | "add" inserts a new header, "edit" replaces an existing header's value, "remove" drops the header. |
| name | string | Header name the action applies to. |
| value? | string | Header value for add/edit; ignored for remove. |
| before? | string | Positions an "add" immediately before the named existing header; otherwise the header is appended at the end. Ignored for edit/remove. |
| after? | string | Positions an "add" immediately after the named existing header. Mirror of before; ignored for edit/remove. |
HeaderModificationAction
type aliastype HeaderModificationAction = "add" | "edit" | "remove"Action verb for a HeaderModification.
IceServer
interfaceIceServer 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.
| urls | string[] | ICE server URLs (e.g. turn:relay.example.com:3478?transport=udp). |
| username | string | Short-lived TURN REST username (empty for plain STUN). |
| credential | string | Short-lived TURN REST credential (empty for plain STUN). |
InterceptedRequest
interfaceInterceptedRequest describes an outgoing request captured by a request wait condition or CloudBrowser.waitForAnyRequest.
| method | string | |
| url | string | |
| headers | Header[] | |
| body | string | |
| resourceType | string |
NetworkBodies
type aliastype NetworkBodies = "none" | "text" | "all"Which response bodies a network capture keeps. Kept bodies are not part of the exchange; read them with CloudBrowser.readNetworkBody.
NetworkBody
interfaceA whole captured body, from CloudBrowser.readNetworkBody.
| data | Uint8Array | |
| truncated | boolean | The kept body is shorter than the original; see the exchange's flag. |
NetworkBodyRange
interfaceOne range of a captured body, from CloudBrowser.readNetworkBodyRange.
| data | Uint8Array | The bytes read; empty past the end of the body. |
| totalSize | number | Bytes kept for the body as a whole. |
| truncated | boolean | Matches the exchange's truncated flag for this body. |
NetworkExchange
interfaceNetworkExchange is one request together with the response it received, as reported by CloudBrowser.captureNetwork.
A redirect chain arrives as one exchange per hop: the hops share chainId and count up redirectIndex, so a 302 and the request it points at are two exchanges, each with its own headers and status.
| requestId | string | Unique per hop. |
| chainId | string | Shared by every hop of one redirect chain. |
| redirectIndex | number | 0 for the original request, incremented once per redirect followed. |
| frameId | string | The frame that issued the request; empty for worker traffic. |
| isOopif | boolean | Whether that frame runs in its own process. Capture happens in the browser process, so cross-process iframes are included. |
| resourceType | NetworkResourceType | |
| method | string | |
| url | string | |
| initiatorUrl | string | The origin that started the request; empty when the browser itself did. |
| requestHeaders | Header[] | |
| requestHeadersAreWire | boolean | Whether requestHeaders are the bytes actually sent — Cookie, User-Agent and Sec-* included — rather than what the page asked for before the network stack filled in the rest. |
| requestBodyId | string | Names the request body; read it with CloudBrowser.readNetworkBody. Empty when the request had no body. Bodies never travel with the exchange. |
| requestBodySize | number | Bytes kept for the request body. |
| requestBodyTruncated | boolean | Part of the request body is missing: it hit the per-body cap, or its source failed before all of it was read. File and streamed uploads are kept like any other body. |
| hasResponse | boolean | False when the request failed before any response arrived; see error. |
| statusCode | number | |
| statusText | string | |
| mimeType | string | |
| protocol | string | Negotiated ALPN protocol, e.g. "h2" or "http/1.1". |
| remoteAddress | string | |
| servedFrom | NetworkServedFrom | |
| responseHeaders | Header[] | |
| responseHeadersAreWire | boolean | |
| responseBodyId | string | Names the response body; read it with CloudBrowser.readNetworkBody. Empty when body capture did not apply to this exchange — see NetworkCaptureOptions.bodies. |
| responseBodySize | number | Bytes kept for the response body, after content decoding. |
| responseBodyTruncated | boolean | The kept body is shorter than the one the page received: it hit the per-body cap or the load ended early. |
| encodedDataLength | number | Bytes on the wire, not body size; 0 for a response served from cache. |
| error | string | Net error name (e.g. "net::ERR_ABORTED"), empty on success. |
NetworkExchangeHandler
type aliastype NetworkExchangeHandler = (exchange: NetworkExchange) => voidNetworkExchangeHandler 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.
NetworkResourceType
type aliastype 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.
NetworkServedFrom
type aliastype 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
interfaceProxyConfig is the session's proxy as the browser uses it. An empty host means a direct connection. masque is the HTTP/3 MASQUE proxy, if any.
| scheme | string | |
| host | string | |
| port | number | |
| username | string | |
| password | string | |
| masque | string |
ProxyScheme
type aliastype 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.
ReactionFiredEvent
interfaceA reaction clicked on page, or tried to. See ContextEvent.
| kind | "reactionFired" | |
| page | Page | |
| reactionId | string | The id Page.addReaction or CloudBrowser.addReaction returned. |
| frameId | string | The frame the match was found in. |
| success | boolean | Whether the click was carried out. |
| interruptedCommand? | string | The 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
interfaceRect describes a position and size in CSS pixels.
| x | number | |
| y | number | |
| width | number | |
| height | number |
RequestPattern
interfaceRequestPattern matches a URL pattern in waitForAnyRequest/Response. Set abort to true to drop the request with an empty 200 response instead of letting it through to the network.
| url | string | |
| abort? | boolean | Default false. |
ScriptEvent
interfaceOne item on a session's script event stream. Exactly one of log and finished is set.
| runId | string | The run that produced this event. |
| log? | ScriptLogEntry | A console line the script printed. |
| finished? | ScriptFinished | The end of the run. No further event for that run follows. |
ScriptEventHandler
type aliastype ScriptEventHandler = (event: ScriptEvent) => voidScriptEventHandler 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.
ScriptLogEntry
interfaceOne console.* call from a script.
| level | string | "info", "warning" or "error", from console.log / .warn / .error. |
| message | string | The logged arguments, already stringified the way console does it. |
| timestamp | Date | When the script printed the line, stamped in the browser. |
SelectorMatch
interfaceWhich of a CSS selector's matches a call took when it was not simply the first.
Where an element has to be visible (a css wait condition or reaction, and every action), a selector means its first rendered match: matches that are not rendered at all (display:none, visibility:hidden, no size) are passed over, so a hidden copy such as the one in a closed mobile menu does not shadow the visible element. A covered or offscreen match is still rendered and stays the target. Set only when the selector matched several elements and the call looked past the first: on a later match it took, or, with index 0, when none of them is rendered.
| index | number | 0-based position among the selector's matches in document order. |
| count | number | How many elements the selector matched. |
SessionUsage
interfaceSessionUsage 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.
| wallTime | number | Real time since the session's browser was created, in seconds. |
| cpuTime | number | User plus kernel CPU time in seconds. Only time a thread actually ran on a core counts; waiting and idling do not. |
| minMemory | number | The least memory the session held once its browser was ready, in bytes. Sampled about once a second. |
| averageMemory | number | The memory held, averaged over wallTime, in bytes; averageMemory * wallTime is the memory-time used. Sampled about once a second, so short spikes count toward the peak but barely toward the average. |
| peakMemory | number | The most memory held at any one moment, in bytes. |
| renderersUsed | number | Renderer processes that hosted at least one of the session's frames: one per site its pages and cross-site iframes needed. |
| framesCreated | number | Child frames created in the session's pages, whether or not they got a process of their own. |
| bytesReceived | number | Bytes 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. |
| bytesSent | number | Bytes they sent the same way: HTTP requests with headers and bodies, and WebSocket messages. |
StorageItem
interfaceStorageItem is a single localStorage key/value pair.
| key | string | |
| value | string |
StorageOriginEntry
interfaceStorageOriginEntry groups the localStorage entries of one origin (e.g. "https://example.com"). getStorage() returns these and setStorage() accepts the same shape, so a dump can be fed back verbatim.
| origin | string | |
| items | StorageItem[] |
UaBrand
interfaceUaBrand is one brand/version pair of the User-Agent client hints. For brands the version is the significant (major) version; for fullVersionList the full version.
| brand | string | |
| version | string |
WaitCaptcha
interfaceThe challenge a captcha wait condition matched.
| kind | string | The type of challenge, a short stable name such as "turnstile". |
| frame | FrameRef | The frame the challenge was found in. |
WaitCondition
type aliastype WaitCondition = Locator | CaptchaCondition | RequestCondition | ResponseConditionAnything Page.wait/Page.waitAny accepts: an element Locator (css / js), captcha, request or response.
WaitConditionStatus
interfaceWaitConditionStatus is the per-condition diagnostic carried by WaitError when a Page.wait times out: one entry per condition (in the order they were passed) explaining why it never matched.
| index | number | Index into the condition list this entry describes. |
| state | string | Last observed state: "not_found", "found_hidden", "found_occluded" (only when the condition required visibility), "pending_steady", or "not_seen" for a request / response condition that never saw a matching request. |
| ref? | Locator | Names the element last seen for this condition; undefined if it was never found or the match was not an element. |
| frameId | string | frameId where it was last seen (empty if never found). |
| scopeError? | string | Set when the condition could not even be looked for at the last look, because a container given with Locator.in led nowhere: it says which link of the chain, and what was missing. state is "not_found" then. |
| isVisible | boolean | Whether it was CSS-visible at the last observation. |
| bounds? | Rect | Last known rect in root-viewport coordinates (undefined if never found). |
| occluder? | OccluderInfo | The intercepting element, present iff state === "found_occluded". |
| selectorMatch? | SelectorMatch | Set when the selector matched several elements and this status is about one other than the first, or none of them is rendered. |
WaitElement
interfaceThe element a css or js wait condition matched.
| ref? | Locator | Names the matched element: pass it to any action to act on exactly this element, or to Locator.in to look inside it. No frame has to be named with it. Undefined when a js() expression matched with a truthy value that is not an element. See ref for how long it stays good. |
| frame | FrameRef | The frame the element lives in (for a non-element match, the frame the expression ran in). |
| isVisible | boolean | Whether the element was visible at the match. |
| bounds | Rect | The element's rect in root-viewport CSS pixels. |
| selectorMatch? | SelectorMatch | Set when a css condition matched an element other than the selector's first match. |
WaitKind
type aliastype WaitKind = WaitResult["kind"]The kind of a WaitResult.
WaitUntil
type aliastype WaitUntil = "load" | "domcontentloaded" | "networkidle"Lifecycle event Page.navigate waits for before returning.