Targeting elements
Almost every browserscale method needs to know which element on the page you
mean — a button to click, an input to fill, something to wait for. The
answer is always a Locator. This guide explains the ways to build
one, how to say where on the page it is looked for, and the small set
of rules that govern which one to reach for in practice.
- A
Locatoris one declarative object — the same object works as a wait condition and as an action target. - Three ways to name an element:
CSS(selector),JS(expression), or theRefan earlier result handed back.At(x, y)names a point instead. - A selector is looked for on the whole page, iframes included.
.In(container)confines it to an iframe, a frame, a dialog or a component. - Two modifiers for waits:
.Visible(...)and.Steady(...). - Defaults already cover the 95 % case — you mostly write
CSS(...)and nothing else.
One object, two uses
Before we dig into the constructors, hold on to the central idea: a
Locator is built once and reused. The same object you pass to Wait
is what you pass to Click, Fill, Drag or any other action.
target := browserscale.CSS("button.submit")
// Use it as a wait condition…
_, _ = page.Wait(ctx, target)
// …then act on it.
_, _ = page.Click(ctx, target)const target = css("button.submit");
// Use it as a wait condition…
await page.wait(target);
// …then act on it.
await page.click(target);That's the mental model the whole guide leans on. Now the constructors.
The constructors
CSS(selector) — your default
Use a standard CSS selector and let the server find the element. This is the right answer for almost every locator you will ever write.
browserscale.CSS("button.submit")
browserscale.CSS("input[name='email']")
browserscale.CSS("#sidebar > .item:first-child")css("button.submit");
css("input[name='email']");
css("#sidebar > .item:first-child");A few things to know:
- The whole page is searched. The main document first, then every
iframe, same-origin or not, at any depth. A button inside a consent
or payment iframe needs no frame named, and the result's
Framesays where it was found.Inconfines the search when you want to say where. - The first rendered match wins. Matches that aren't 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 or an inactive tab doesn't shadow the visible element. A covered or offscreen match still counts and stays the target; a click then reports what covers it. When a later match was taken, the result says which one inSelectorMatch(selectorMatchin TS): its index and how many matched. If you need a specific one of many, narrow the selector. - Only standard CSS is supported. jQuery-style extensions like
:contains("text")won't work — for text-content matches reach forJS(...)instead. - When used as a wait condition, the SDK silently attaches two defaults
(
Visible(true),Steady(500)). Those are explained in the modifier section below; for now just know thatCSS("button.submit")already means "a button.submit that is visible and not animating".
JS(expression) — when CSS isn't expressive enough
Pass any JavaScript expression. It is evaluated in the page's main
document — or, with In, in the frame
you put it in — and what comes back decides. JS has two modes, and which
one is active depends on the expression's return value:
- Returns a DOM Element → behaves exactly like
CSS(...)from that point on. Visibility and steady checks apply. - Returns a truthy non-Element value (boolean, number, string, plain object) → matches as soon as the value is truthy. Visibility and steady are silent no-ops because there is no element to measure.
Mode 1 is the escape hatch for selectors CSS can't express:
// Click a button by its text content — impossible in plain CSS.
target := browserscale.JS(`
Array.from(document.querySelectorAll('button'))
.find(b => b.textContent.trim() === 'Submit')
`)
_, _ = page.Click(ctx, target)// Click a button by its text content — impossible in plain CSS.
const target = js(`
Array.from(document.querySelectorAll('button'))
.find(b => b.textContent.trim() === 'Submit')
`);
await page.click(target);Mode 2 is for waiting on state that has no DOM equivalent:
// Wait for an app-level "I'm ready" flag.
_, _ = page.Wait(ctx, browserscale.JS("window.__ready === true"))
// Wait for a network request that updated a Redux store.
_, _ = page.Wait(ctx, browserscale.JS("store.getState().user.id !== null"))// Wait for an app-level "I'm ready" flag.
await page.wait(js("window.__ready === true"));
// Wait for a network request that updated a Redux store.
await page.wait(js("store.getState().user.id !== null"));JS is powerful, but it also runs your code in the page. Keep
expressions short and side-effect-free — anything observable from JS
is also observable to the site you are automating.
References
Every action and wait hands back a reference to the element it
found, as a ready Locator in the result's Ref. Pass it to the next
call and that call acts on that exact element, without looking
anything up again:
// Open a dropdown, then click the same trigger again to close it.
res, _ := page.Click(ctx, browserscale.CSS("button.dropdown-trigger"))
_, _ = page.Click(ctx, res.Ref)
// What a wait found, acted on.
found, _ := page.Wait(ctx, browserscale.CSS(".result"))
_, _ = page.Click(ctx, found.Element.Ref)// Open a dropdown, then click the same trigger again to close it.
const res = await page.click(css("button.dropdown-trigger"));
await page.click(res.ref!);
// What a wait found, acted on.
const found = await page.wait(css(".result"));
await page.click(found.element.ref!);A reference names its element together with the document it lives in. That has three consequences:
- No frame goes with it. An element found inside an iframe is
acted on through its reference alone;
Indoes not apply. - It can be a container. A reference to an iframe, a dialog or a
component works in
Inlike a selector for it would. - It goes stale instead of pointing elsewhere. 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 fails with a
StaleRefErrorrather than acting on whatever took its place:
_, err := page.Click(ctx, found.Element.Ref)
var stale *browserscale.StaleRefError
if errors.As(err, &stale) {
// The document is gone; stale.URL is where the page is now. Look again.
found, _ = page.Wait(ctx, browserscale.CSS(".result"))
_, err = page.Click(ctx, found.Element.Ref)
}try {
await page.click(found.element.ref!);
} catch (err) {
if (!(err instanceof StaleRefError)) throw err;
// The document is gone; err.url is where the page is now. Look again.
const again = await page.wait(css(".result"));
await page.click(again.element.ref!);
}A reference can also arrive as text. An
observation prints one line per frame saying
# ref @<document>; a row's number followed by that suffix is the
element's reference, and Ref(...) turns it into a Locator. The other
direction is RefString(), for writing a reference down within a
session.
// Row 47 of the frame whose header says "# ref @9F2C41D0...".
_, err := page.Click(ctx, browserscale.Ref("47@9F2C41D0A1B24C7E8F3A5D6B7C8E9F01"))// Row 47 of the frame whose header says "# ref @9F2C41D0...".
await page.click(ref("47@9F2C41D0A1B24C7E8F3A5D6B7C8E9F01"));References are action-only: passing one to Wait is rejected at
send time — a wait needs a selector or an expression so the page has
something to watch.
At(x, y) — pixel coordinates
Sometimes the thing you want to click is not addressable through the
DOM at all: a canvas pixel, a captcha grid cell, an HTML5 game
element. At(x, y) skips element resolution entirely and dispatches
the action at the given viewport-relative CSS-pixel coordinates.
// Click somewhere on a canvas.
_, _ = page.Click(ctx, browserscale.At(420, 580))// Click somewhere on a canvas.
await page.click(at(420, 580));The catch: At is only accepted by Click and MoveTo. Anything
else (Drag, Fill, ScrollTo, Select…) needs a real element so
the server can scroll it into view first. Trying to pass At to one
of those returns an error before the request ever leaves your machine.
Which constructor goes where
Quick reference for "can I use this locator with that method?".
| Constructor | Wait | Click, MoveTo | Fill, Select…, Drag, ScrollTo |
|---|---|---|---|
CSS(...) | yes | yes | yes |
JS(...) | yes | yes | yes |
| a reference | no — nothing to watch | yes | yes |
At(...) | no — needs an element | yes | no — needs an element |
The no cells are validated client-side before the request goes out,
so you get an immediate, descriptive error instead of a confusing
server-side failure.
The modifiers
Each modifier is a method on the Locator that returns a Locator, so
they chain in any order. There is a subtle difference in how
Visible and Steady behave in Go vs TS — covered at the end of
this section.
Visible(bool) — wait-only
When the Locator is used as a wait condition, the matched element must
be visible to count: not display:none, not visibility:hidden,
non-zero size. This is the default and is what you want almost always
— without it, Wait happily returns on hidden elements that the user
can't even see.
Pass false when you specifically need to wait for a hidden element:
// Wait for an off-screen container to exist (display:none for now).
_, _ = page.Wait(ctx, browserscale.CSS("#hidden-form").Visible(false))// Wait for an off-screen container to exist (display:none for now).
await page.wait(css("#hidden-form").visible(false));With Visible(false) a CSS condition takes the selector's first match,
rendered or not.
Visible has no effect on actions — an action always takes the
first rendered match and fails with not_visible when there is none.
Steady(ms) — wait-only
Real pages animate. Banners slide in, modals fade, lists lazy-load their layout, iframes get pushed around when an ad finishes rendering. A wait that fires the moment the element appears can dispatch a click while the target is mid-flight.
Steady(ms) says "don't match until the element's bounding rect
hasn't moved for this many milliseconds". Default is 500 ms, which
covers most CSS animations and pulled-in iframes.
// A slow-settling CTA — wait a full second of stability before matching.
_, _ = page.Wait(ctx, browserscale.CSS("button.cta").Steady(1000))
// Plain text that never animates — match the instant it appears.
_, _ = page.Wait(ctx, browserscale.CSS(".status-line").Steady(0))// A slow-settling CTA — wait a full second of stability before matching.
await page.wait(css("button.cta").steady(1000));
// Plain text that never animates — match the instant it appears.
await page.wait(css(".status-line").steady(0));Two things to remember:
- Wait-only, like
Visible. Actions never re-measure. - No-op on
JSexpressions that return a non-Element value — there is no bounding rect to measure for a boolean.
In(container) — where to look
In confines a Locator to a container, for waits and actions alike.
The container is itself a Locator, and what it means depends on what
it finds:
- an iframe element — the element is looked for in that iframe's document, same-origin or not;
- any other element — in its subtree, including its shadow tree, open or closed;
- a frame named directly —
FrameURL(pattern),FrameName(name),FrameByID(id),MainFrame(),AnyFrame().
// Inside an iframe, named by its element.
pay := browserscale.CSS("iframe[title='Secure payment']")
_, _ = page.Fill(ctx, browserscale.CSS("input[name=cardnumber]").In(pay), card)
// Inside a frame, named by the URL it shows.
challenge := browserscale.FrameURL("*hcaptcha.com/*frame=checkbox*")
_, _ = page.Click(ctx, browserscale.CSS("#checkbox").In(challenge))
// Inside a dialog; inside a component with a shadow tree.
_, _ = page.Click(ctx, browserscale.CSS("button.close").In(browserscale.CSS("[role=dialog]")))
_, _ = page.Click(ctx, browserscale.CSS("button.next").In(browserscale.CSS("date-picker")))
// Only the page's own document, no iframe.
_, _ = page.Click(ctx, browserscale.CSS("button.accept").In(browserscale.MainFrame()))// Inside an iframe, named by its element.
const pay = css("iframe[title='Secure payment']");
await page.fill(css("input[name=cardnumber]").in(pay), card);
// Inside a frame, named by the URL it shows.
const challenge = frameUrl("*hcaptcha.com/*frame=checkbox*");
await page.click(css("#checkbox").in(challenge));
// Inside a dialog; inside a component with a shadow tree.
await page.click(css("button.close").in(css("[role=dialog]")));
await page.click(css("button.next").in(css("date-picker")));
// Only the page's own document, no iframe.
await page.click(css("button.accept").in(mainFrame()));Containers nest — FrameURL(inner).In(outer) is a frame inside a
frame — and the whole chain is looked up anew each time the call
looks for its element, so a call that waits also waits for its
container. In returns a new Locator in both languages and leaves
the container untouched: keep a container in a variable and reuse it.
Without In, a CSS locator means the whole page and a JS locator
the main document. To have an expression asked in every frame, put it
in AnyFrame().
The Frames & iframes guide goes through every kind of container, nesting, and what comes back.
A subtle Go vs TS difference
Visible and Steady feel chainable in both languages, but the
implementations differ:
// In Go, Visible and Steady change the Locator in place and return the same pointer.
base := browserscale.CSS(".banner")
base.Steady(0) // <-- changes base!
// base now has steady=0// In TS every modifier returns a NEW Locator. The original is untouched.
const base = css(".banner");
const fast = base.steady(0);
// base still has steady=500, fast has steady=0The practical takeaway: in Go, don't reuse a Locator after calling
Visible or Steady on it unless you mean to apply them
everywhere. In is different: it returns a new Locator in Go too, so
a base Locator or a container can be shared freely.
Recipes
A handful of patterns that come up over and over:
Click a button by its visible text. CSS can't, so use JS:
target := browserscale.JS(`
Array.from(document.querySelectorAll('button'))
.find(b => b.textContent.trim() === 'Sign in')
`)
_, _ = page.Click(ctx, target)const target = js(`
Array.from(document.querySelectorAll('button'))
.find(b => b.textContent.trim() === 'Sign in')
`);
await page.click(target);Wait for an arbitrary JS condition. No element involved:
_, _ = page.Wait(ctx, browserscale.JS("performance.timing.loadEventEnd > 0"))await page.wait(js("performance.timing.loadEventEnd > 0"));Wait for an element that is in the DOM but hidden. Classic case: a hidden CSRF input that the page injects after a network round-trip. The default visibility check would never match, so opt out:
_, _ = page.Wait(ctx, browserscale.CSS("input[name='csrf_token']").Visible(false))await page.wait(css("input[name='csrf_token']").visible(false));Click the same element twice without re-resolving. Use the
returned Ref:
r, _ := page.Click(ctx, browserscale.CSS("button.toggle"))
_, _ = page.Click(ctx, r.Ref)const r = await page.click(css("button.toggle"));
await page.click(r.ref!);Click a specific captcha cell. Use coordinates from
InspectAtPosition or your own image-recognition pipeline:
_, _ = page.Click(ctx, browserscale.At(420, 580))await page.click(at(420, 580));Click a button wherever it lives. A selector is looked for in every frame; the result says which one it was:
r, _ := page.Click(ctx, browserscale.CSS("button.dismiss"))
fmt.Println(r.Frame.URL)const r = await page.click(css("button.dismiss"));
console.log(r.frame.url);Click a button by its text, in whichever frame has it. An expression only searches the frames when told to:
_, _ = page.Click(ctx, browserscale.JS(`
[...document.querySelectorAll('button')].find(b => b.innerText === 'Accept all')
`).In(browserscale.AnyFrame()))await page.click(js(`
[...document.querySelectorAll('button')].find(b => b.innerText === 'Accept all')
`).in(anyFrame()));Gotchas to keep in mind
A short list of things that cause confusion on day one:
- A reference or
At()as a wait condition is rejected before the request leaves the SDK. Wait needs something to watch — a selector or a JS expression — and neither of these provides one. - A reference or
At()takes noIn. A reference already names its document, and a point is a point in the page's viewport. - The frame constructors are containers only.
FrameURL(...)and its siblings say where to look; passing one as the target of a click is rejected. Visible/Steadyon actions are silently ignored. They only affect wait. If you want to gate an action on visibility, do an explicitWaitfirst, then act.- JS expressions returning non-Element values make
VisibleandSteadyno-ops. The condition matches as soon as the value is truthy — there is nothing to measure. - Locator equality isn't a thing — two
CSS("button")calls produce two distinct Locator objects with equal contents. To tell whether two results mean the same element, compare their references (Ref.RefString()). - Building the
Locatorstruct/class by hand is discouraged. Go has unexported fields and TS has a private constructor specifically to push you toward the factory functions.
- The Waiting guide covers multi-condition races, custom timeouts, and why you need to wait explicitly before acting.
- The Frames & iframes guide goes through containers, nesting and the frame tree.
- API reference: Go locators · TS locators.