Core concepts
Four nouns carry every browserscale script: CloudBrowser, Page,
Locator, and Wait. Once those click into place — plus a
one-paragraph mental model of the session lifecycle — the rest of the SDK
is just method discovery in the API reference.
CloudBrowseris your live handle to a remote browser session: its cookies, storage, network rules, tabs and live stream.Pageis one tab or popup in it. Everything that acts on a document — navigate, wait, click, read — is aPagemethod. A session starts without one;CreatePageopens the first.Locatoris a declarative "which element / under which conditions"; the same object works for both waits and actions.Waitblocks until a Locator matches — but you rarely need it because every action auto-waits.- The session is billed by use while it runs, out of your balance; nothing is taken upfront when you rent.
CloudBrowser
CloudBrowser is the gRPC-backed handle you receive from RentBrowser.
Think of it as a small, stateful client to one specific browser context:
every method on it is one round-trip to the server, and the order matters
(navigate first, click after). What belongs to the whole context lives
here — cookies, storage, network rules and capture, the list of tabs, the
live stream.
A fresh session has no tab yet. CreatePage opens the first one, the way
opening a new tab does: an about:blank tab that takes the focus, ready to
navigate by the time the call returns.
browser, err := browserscale.RentBrowser(ctx, cfg)
if err != nil { log.Fatal(err) }
defer browser.Close()
page, err := browser.CreatePage(ctx)
if err != nil { log.Fatal(err) }
_, _ = page.Navigate(ctx, "https://browserscale.cloud", 0)const browser = await rentBrowser(cfg);
try {
const page = await browser.createPage();
await page.navigate("https://browserscale.cloud");
} finally {
await browser.stopBrowser();
}The handle is not safe to share across goroutines or async contexts — every call serialises on the underlying gRPC stream, so concurrent use just queues. If you need real parallelism, rent a second session.
Page
A Page is one tab or popup of the session. It holds nothing but the
page's id, so it never goes stale on its own: which pages exist and which
one is in front is the browser's to know, and it behaves like a real one.
A link with target=_blank or a window.open opens a new page that comes
to the front, and closing the page in front hands the focus back, usually
to the page that opened it.
| Call | What it does |
|---|---|
CreatePage | Opens a new tab that takes the focus |
FocusedPage | The page in front — the one a person would be looking at |
Pages | Every page with its URL, title, frame tree, opener and whether it has the focus |
GetPage(id) | The handle for a page id you already have; makes no call |
page.Focus | Brings the page to the front, like clicking its tab |
page.Close | Closes it like closing its tab, and returns the page in front afterwards |
Reading and evaluating work on any page. Input — Click, MoveTo and
what builds on them — acts only on the page in front, because that is
the only one a person could click. Three errors tell you the tabs
changed under you, and each one hands you the page to carry on with:
| Error (Go / TS) | When |
|---|---|
PageNotFocusedError | An input call hit a page that is not in front, typically because it just opened a tab or popup. FocusedPage is that page. |
PageClosedError | The page has closed. FocusedPage is the page in front now. |
ErrNoPage / NoPageError | FocusedPage or StartStream before the first CreatePage. |
_, err = page.Click(ctx, browserscale.CSS("a.open-in-new-tab"))
var nf *browserscale.PageNotFocusedError
if errors.As(err, &nf) {
page = nf.FocusedPage // the new tab came to the front — continue there
}try {
await page.click(css("a.open-in-new-tab"));
} catch (e) {
if (!(e instanceof PageNotFocusedError)) throw e;
page = e.focusedPage; // the new tab came to the front — continue there
}To follow the tabs as they change instead of discovering it from an
error, register a listener with ContextEvents. It first reports every
page, then each one opening, closing, coming to the front or changing its
URL or title — enough to keep a tab strip current without polling
Pages.
listener, err := browser.ContextEvents(ctx, func(ev browserscale.ContextEvent) {
switch ev.Kind {
case browserscale.ContextEventSnapshot:
fmt.Println("pages:", len(ev.Pages))
case browserscale.ContextEventPageOpened:
fmt.Println("opened", ev.Opened.Url)
case browserscale.ContextEventPageFocused:
fmt.Println("in front:", ev.Page.Id())
case browserscale.ContextEventPageClosed:
fmt.Println("closed", ev.Page.Id(), "- in front:", ev.FocusedPage.Id())
case browserscale.ContextEventPageUpdated:
fmt.Println(ev.Page.Id(), "is now", ev.Url)
}
})
if err != nil { log.Fatal(err) }
defer listener.Stop()const listener = await browser.contextEvents((ev) => {
switch (ev.kind) {
case "snapshot": console.log("pages:", ev.pages.length); break;
case "pageOpened": console.log("opened", ev.info.url); break;
case "pageFocused": console.log("in front:", ev.page.id); break;
case "pageClosed": console.log("closed", ev.page.id, "- in front:", ev.focusedPage.id); break;
case "pageUpdated": console.log(ev.page.id, "is now", ev.url); break;
}
});
// … later
await listener.stop();Locator
A Locator answers "which element on the page do I mean?". The same
Locator object is what you pass to Click, Fill, Drag — and what you
pass to Wait. One declarative thing, two uses.
The constructors
| Constructor | What you give it | When to reach for it |
|---|---|---|
CSS(selector) | A CSS selector string | Your default — almost every locator you ever write |
JS(expression) | A JS expression that returns an Element or a truthy value | When CSS can't describe it (text content, computed state, custom logic) |
a result's Ref | Nothing — every result carries one for the element it found | Acting on exactly the element Wait / Click / Evaluate already found, without re-resolving |
At(x, y) | Viewport coordinates in CSS pixels | Pixel-precise hits (canvas, captcha cells) — accepted by Click and MoveTo only |
You usually need nothing else
The thing to internalise is that CSS(...) is already complete. When
you write it, the SDK quietly attaches two sensible defaults: the element
must be visible, and its bounding rect must hold still for 500 ms before
the wait matches. That covers the 95 % case — buttons that fade in, modals
that slide, list items that lazy-load — without you thinking about it.
// 95% case — nothing extra. Auto-waits for visible + steady.
_, _ = page.Click(ctx, browserscale.CSS("button.submit"))// 95% case — nothing extra. Auto-waits for visible + steady.
await page.click(css("button.submit"));You only reach for modifiers when those defaults need to bend:
// Element is deliberately offscreen (display:none) — opt out of visible.
_, _ = page.Click(ctx, browserscale.CSS(".lazy-mounted").Visible(false))
// You want to fire as soon as it appears — skip the 500ms steady wait.
_, _ = page.Click(ctx, browserscale.CSS(".banner").Steady(0))
// Look in one place — an iframe, a dialog, a component — instead of the whole page.
_, _ = page.Click(ctx, browserscale.CSS("button.pay").In(browserscale.CSS("iframe.checkout")))// Element is deliberately offscreen (display:none) — opt out of visible.
await page.click(css(".lazy-mounted").visible(false));
// You want to fire as soon as it appears — skip the 500ms steady wait.
await page.click(css(".banner").steady(0));
// Look in one place — an iframe, a dialog, a component — instead of the whole page.
await page.click(css("button.pay").in(css("iframe.checkout")));A selector is looked for on the whole page, iframes included, and the
result says which frame it was in — so the last one is for when you
want to say where. The full modifier set is .Visible / .Steady / .In,
all chainable in any order. The Targeting elements guide goes deep on
each one.
Wait
Every element action already waits for its target — Click(ctx, CSS(...))
does not need a separate Wait call in front of it. You reach for Wait
directly only when you want to observe a state change without acting:
confirm a modal appeared, race two possible outcomes, or block on a JS
condition that is not even an element.
The Go API is variadic — conditions and options interleave freely. The TS
API splits the two: wait(condition, opts?) for one, waitAny([...], opts?)
for several.
// Either a success banner or a redirect URL — whichever comes first.
res, err := page.Wait(ctx,
browserscale.CSS(".banner-success"),
browserscale.JS("location.pathname === '/welcome'"),
browserscale.Timeout(5000),
)
if err != nil { log.Fatal(err) }
fmt.Println("matched condition index:", res.Index)// Either a success banner or a redirect URL — whichever comes first.
const res = await page.waitAny(
[css(".banner-success"), js("location.pathname === '/welcome'")],
{ timeoutMs: 5000 },
);
console.log("matched condition index:", res.index);When several conditions are passed, the first one to match wins —
the others are abandoned the instant a winner is found. WaitResult.Index
(.index in TS) tells you which entry won, so you can branch on it.
Session lifecycle
RentBrowser ──▶ CreatePage ──▶ drive (navigate, click, …) ──▶ StopBrowser / Close
│
└── billed by use until it ends: the start, the time it is
open, CPU and memory
Renting needs a balance that carries one more browser next to the ones
you already run; otherwise RentBrowser fails with INSUFFICIENT_CREDITS.
Nothing is taken upfront, and the rentDuration is a limit, not a
reservation.
Four things can end a session:
- You call
StopBrowser(orClosein Go) — the canonical, clean shutdown, and billing stops with it. Always defer this so a panic mid-script still releases the session. - The
rentDurationyou set onNewBrowserConfigexpires — the server tears the session down and any in-flight call returns an error. - Your balance no longer carries it — the session is ended.
- Nothing, if the process holding the handle dies without releasing
it — the session runs on, and is billed, until its
rentDurationends. Keep the duration near what a job needs.
The cleanest pattern: defer browser.Close() (Go) or
try { … } finally { await browser.stopBrowser(); } (TS). It costs
nothing when the script runs to completion and saves a session from
running on, and being billed, when something blows up.
The SDK defaults at a glance
A handful of constants govern "what does browserscale do when I leave the option off?". They are exported so you can read them, and overridable per call:
| Default | Value | Where it applies |
|---|---|---|
DefaultWaitTimeoutMs | 30 000 ms (30 s) | Wait and every action's implicit wait |
DefaultVisible | true | CSS / JS element locators require the match to be visible |
DefaultSteadyMs | 500 ms | CSS / JS element locators require the bounding rect to stop moving for this long |
Translated: by default, every action waits up to 30 seconds for an
element that is on-screen and not animating. You rarely need to think
about this — the moment you do, override per locator with
.Visible(false) / .Steady(0), or per call with Timeout(...).
- The Targeting elements guide walks through every Locator constructor and modifier in depth.
- The Waiting guide covers multi-condition waits, anti-patterns and timeouts.
- The Go SDK reference and TypeScript SDK reference list every method on
CloudBrowser.