Frameworks and the Playground
Notes for connecting particular frameworks to a hosted browser, and the Playground in the dashboard for trying a task or a script while you watch the live view.
Frameworks
Anything that attaches to Chrome over CDP works with the connectUrl. It is single-use, so a framework that reconnects on its own needs a new session for each connection. The browser starts when you connect, usually within a few seconds (see the timeout note above); there is no status to poll first.
// Patchright (optional; a Playwright fork): npm i patchright
import { chromium } from "patchright";
const browser = await chromium.connectOverCDP(connectUrl, { timeout: 120_000 });
const page = browser.contexts()[0].pages()[0];# Browser Use
from browser_use import Agent, Browser
agent = Agent(task="Find the cheapest flight to Lisbon next Friday", llm=llm, browser=Browser(cdp_url=connect_url))
await agent.run()
# Crawl4AI
from crawl4ai import AsyncWebCrawler, BrowserConfig
config = BrowserConfig(browser_mode="custom", cdp_url=connect_url, use_managed_browser=True)
async with AsyncWebCrawler(config=config) as crawler:
result = await crawler.arun("https://example.com")// Stagehand v4
import { localBrowser, Stagehand } from "@browserbasehq/stagehand";
const stagehand = await Stagehand.create({ browser: await localBrowser.connect({ cdpUrl: connectUrl }) });setContent and exposeFunction
The engine never sends console events to the client, because forwarding them is what pages that look for an automation client measure. Hosted browsers keep it that way: the SDK's stock_runtime option, which turns them back on for a debugging run on your own machine or in Docker, is not applied to a cloud launch. Two driver calls depend on them:
- Playwright's
page.setContent()waits for a console event that never comes, so it times out (Puppeteer's works). Open the HTML as adata:URL instead, or write it into the page yourself, as below. exposeFunction()andexposeBinding(), in Playwright and Puppeteer, work in the page that is open when you call them, and are gone once that page navigates. Call them after the last navigation, or pass results back fromevaluateinstead.
// Instead of await page.setContent(html):
// Short HTML: a data: URL (the page gets no origin of its own, so no cookies or storage)
await page.goto("data:text/html," + encodeURIComponent(html));
// Any HTML: write it into a page you have navigated to; it keeps that page's origin
await page.evaluate((html) => {
document.open();
document.write(html);
document.close();
}, html);# Instead of page.set_content(html):
from urllib.parse import quote
page.goto("data:text/html," + quote(html))
# or
page.evaluate("html => { document.open(); document.write(html); document.close(); }", html)A helper to start from
Create with the retries above, connect, and always stop, in one function:
// clearcote-hosted.ts
import { chromium, type Browser } from "playwright"; // or "patchright"
const API = "https://www.clearcotelabs.com/api/v1/browsers";
const AUTH = { authorization: "Bearer " + process.env.CLEARCOTE_API_KEY };
const RETRY_CODES = new Set(["NO_CAPACITY", "NO_WORKER"]);
export async function createSession(options: Record<string, unknown> = {}, attempts = 5) {
for (let i = 0; ; i++) {
const res = await fetch(API, {
method: "POST",
headers: { ...AUTH, "content-type": "application/json" },
body: JSON.stringify(options),
});
const body = await res.json().catch(() => ({}));
if (res.ok) return body as { id: string; connectUrl: string; worker: string };
const retry = RETRY_CODES.has(body.code) || (res.status === 429 && !body.code) || [500, 502, 504].includes(res.status);
if (!retry || i + 1 >= attempts) throw new Error([res.status, body.code, body.error].filter(Boolean).join(" "));
await new Promise((r) => setTimeout(r, Math.min(15_000, 1000 * 2 ** i) * (0.5 + Math.random())));
}
}
export async function withBrowser<T>(options: Record<string, unknown>, work: (browser: Browser) => Promise<T>) {
const session = await createSession(options);
try {
const browser = await chromium.connectOverCDP(session.connectUrl, { timeout: 120_000 });
try {
return await work(browser);
} finally {
await browser.close().catch(() => {});
}
} finally {
// Ends the session if closing the browser did not (a no-op otherwise).
await fetch(API + "/" + session.id, { method: "DELETE", headers: AUTH }).catch(() => {});
}
}
// await withBrowser({ profile: { name: "shop", persist: true }, country: "de" }, async (browser) => {
// const page = browser.contexts()[0].pages()[0];
// await page.goto("https://example.com");
// });Uploading files
A page that asks for a file — an <input type="file">, a “browse” button, a drag-and-drop area — takes one the same way in a hosted browser as in a local one. The file is read on your machine and its bytes travel over the connection, so the browser never sees a path on your disk and you can upload a file that only exists where your script runs. The limit is 50 MB per file.
Playwright is the simplest. setInputFiles puts a file straight into the input, with no click, and works even when the input is hidden — many sites hide the real input behind a styled button, so target the input itself rather than clicking.
// Node.js + Playwright
await page.setInputFiles("input[type=file]", "C:/Users/me/invoice.pdf");
// or build the file in your script, with nothing on disk:
await page.setInputFiles("input[type=file]", {
name: "invoice.pdf",
mimeType: "application/pdf",
buffer: Buffer.from("%PDF-1.4 …"),
});# Python + Playwright
page.set_input_files("input[type=file]", "/home/me/invoice.pdf")When a button opens the system file dialog and there is no input you can target, catch the chooser instead:
const [chooser] = await Promise.all([
page.waitForEvent("filechooser"),
page.click("text=Browse"), // the page's own button
]);
await chooser.setFiles("C:/Users/me/invoice.pdf");Puppeteer. elementHandle.uploadFile() and fileChooser.accept() are not available on hosted browsers: they name a path for the server to read, which could point anywhere on the worker, so the gateway refuses them. Build the file inside the page from bytes you send in, and hand it to the input:
// Puppeteer: construct the file in the page
const b64 = fs.readFileSync("invoice.pdf").toString("base64");
await page.evaluate(({ b64, name, type }) => {
const data = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
const dt = new DataTransfer();
dt.items.add(new File([data], name, { type }));
const input = document.querySelector("input[type=file]");
input.files = dt.files;
input.dispatchEvent(new Event("change", { bubbles: true }));
}, { b64, name: "invoice.pdf", type: "application/pdf" });The same DataTransfer drives a drag-and-drop zone: dispatch dragenter, dragover and drop on it carrying that object. A real CDP drag with a local path (Input.dispatchDragEvent with files) is refused for the same reason as uploadFile().
Downloading files
A file the page downloads is saved on our server, in the session’s own folder. You fetch it over the connection your script already has, with four commands that the hosted gateway answers itself: the Hosted domain, sent on any CDP session. The folder is deleted when the session ends, so fetch what you need before you close the browser.
Playwright saves each download under an id. Hosted.listFiles shows that id as the file’s name and adds the name the site gave the file, so match on suggestedFilename():
// Node.js + Playwright
const cdp = await browser.newBrowserCDPSession();
const [download] = await Promise.all([
page.waitForEvent("download"),
page.click("text=Export"), // whatever starts the download
]);
// Wait until the browser has finished writing it.
const isIt = (f) => f.download?.suggestedFilename === download.suggestedFilename() && f.download.state === "completed";
let file;
while (!(file = (await cdp.send("Hosted.listFiles")).files.find(isIt))) {
await new Promise((r) => setTimeout(r, 250));
}
// Read it in chunks (4 MB each unless you pass length, 8 MB at most).
const parts = [];
for (let offset = 0, eof = false; !eof; ) {
const chunk = await cdp.send("Hosted.readFile", { name: file.name, offset });
parts.push(Buffer.from(chunk.data, "base64"));
offset += chunk.bytes;
eof = chunk.eof;
}
fs.writeFileSync(download.suggestedFilename(), Buffer.concat(parts));
await cdp.send("Hosted.deleteFile", { name: file.name }); // frees room in the session's folder# Python + Playwright
import base64, time
cdp = browser.new_browser_cdp_session()
with page.expect_download() as info:
page.click("text=Export")
name = info.value.suggested_filename
def find():
for f in cdp.send("Hosted.listFiles")["files"]:
d = f.get("download") or {}
if d.get("suggestedFilename") == name and d.get("state") == "completed":
return f
file = find()
while not file:
time.sleep(0.25)
file = find()
data, offset = b"", 0
while True:
chunk = cdp.send("Hosted.readFile", {"name": file["name"], "offset": offset})
data += base64.b64decode(chunk["data"])
offset += chunk["bytes"]
if chunk["eof"]:
break
cdp.send("Hosted.deleteFile", {"name": file["name"]})Puppeteer and other clients that leave the download settings alone get the file under the name the site gave it. It appears once the download is complete; until then the browser writes a .crdownload file, listed with partial: true.
// Puppeteer
const cdp = await page.createCDPSession();
await page.click("#export");
let file;
while (!(file = (await cdp.send("Hosted.listFiles")).files.find((f) => f.name === "report.csv"))) {
await new Promise((r) => setTimeout(r, 250));
}
const { data, eof } = await cdp.send("Hosted.readFile", { name: file.name }); // loop on offset for files over 4 MB| Command | Takes | Returns |
|---|---|---|
Hosted.listFiles | nothing | files: name, size, modified (ms), partial, and download (suggestedFilename, url, state) for a download Playwright named; plus totalBytes and limits. |
Hosted.readFile | name, offset (0), length (4 MB, at most 8 MB) | data (base64), offset, bytes, size, eof |
Hosted.deleteFile | name | nothing |
Hosted.writeFile | name, data (base64, at most 8 MB per call), append | name, size |
A name is always one file name exactly as listFiles returns it, never a path. The folder holds at most 1 GB, downloads and files you put in together. A browser that downloads past that ends the session (reason max_files_size), so delete what you have fetched in a long session.
Hosted.writeFile puts a file into the session’s folder, to read back later in the same session: up to 50 MB per file, sent in calls of at most 8 MB with append: true for the rest. Executable file types (.exe, .bat, .ps1 and the like) are refused. A page cannot open files from that folder; to give a page a file, use setInputFiles as in Uploading files.
The Playground
The Playground in the dashboard runs one of these browsers while you watch it in the live view. It opens on Task: write what the browser should do, and an agent does it step by step. That is an agent run, the same as POST /api/v1/runs, and each step shows under What it did as it happens. You can take control in the live view whenever you like. With Ask me when it gets stuck on (it is by default), the agent pauses when it needs a person, for a sign-in code for example, and carries on once you mark it done.
The chips under the task set where it starts (Start at), the country of its residential IP (Exit), whether it is a fresh device or one that comes back (Device), and whether the answer is text or JSON in a shape you give (Output). More holds every other session option, the most steps it may take, a video recording, and secrets: write {{password}} in the task and add its value there. The model only sees the placeholder, and the value stays in your tab: it is never saved and never part of a link.
Script runs your own code instead. It runs in a sandboxed frame in your tab and speaks CDP to the browser over its WebSocket. log() prints under What it did, and under More you can keep the browser open so the next script continues in it. Its page is a small helper, not Playwright, so a Playground script is a sketch to translate, not a file to paste:
| Helper | Does |
|---|---|
page.goto(url, { timeout? }) | Navigate and wait for the load event. |
page.click(sel) · page.type(sel, text) · page.press(key) | Real mouse and keyboard input, scrolled into view first. |
page.evaluate(fn, ...args) | Run a function in the page and get its JSON result back. |
page.waitForSelector(sel, { timeout? }) · page.waitForNavigation() | Wait for an element, or for the next page load. |
page.scroll(px) · page.screenshot({ fullPage? }) | Mouse-wheel scroll; a JPEG that shows in the run's result. |
page.title() · page.url() · page.content() | The document title, address and HTML. |
log(...values) · sleep(ms) | Print a line under What it did (objects are pretty-printed); pause. |
cdp(method, params) | A raw CDP command to the browser (Target.*, Browser.*, Storage.*). |
page.cdp(method, params) | A raw CDP command to the page (Page.*, Runtime.*, DOM.*, Network.*). |
Errors report the script line they came from. Save as… keeps a script in this browser.
When a run ends, its result shows under it: a task's answer and the page it ended on, with the recording if you asked for one and the run's full timeline, or a script's captures. The result offers the same run three more ways. Use in code shows it as code for your own project: a task as a call to the runs API in Node, Python or curl, a script as the same browser and options for Playwright or Puppeteer. Copy for AI copies a prompt for a coding agent with the API, this run and its options. Share copies a link that carries the task or script and its options in the URL, so nothing is stored on our side; whoever opens it runs it on their own balance. None of the three carries a secret's value.