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.

TL;DR
  • A Locator is 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 the Ref an 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)

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")

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 Frame says where it was found. In confines 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 in SelectorMatch (selectorMatch in 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 for JS(...) 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 that CSS("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:

  1. Returns a DOM Element → behaves exactly like CSS(...) from that point on. Visibility and steady checks apply.
  2. 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)

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"))

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)

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; In does not apply.
  • It can be a container. A reference to an iframe, a dialog or a component works in In like 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 StaleRefError rather 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)
}

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"))

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

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

ConstructorWaitClick, MoveToFill, Select…, Drag, ScrollTo
CSS(...)yesyesyes
JS(...)yesyesyes
a referenceno — nothing to watchyesyes
At(...)no — needs an elementyesno — 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))

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

Two things to remember:

  • Wait-only, like Visible. Actions never re-measure.
  • No-op on JS expressions 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()))

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

The 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)

Wait for an arbitrary JS condition. No element involved:

_, _ = page.Wait(ctx, browserscale.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))

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)

Click a specific captcha cell. Use coordinates from InspectAtPosition or your own image-recognition pipeline:

_, _ = page.Click(ctx, browserscale.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)

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()))

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 no In. 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 / Steady on actions are silently ignored. They only affect wait. If you want to gate an action on visibility, do an explicit Wait first, then act.
  • JS expressions returning non-Element values make Visible and Steady no-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 Locator struct/class by hand is discouraged. Go has unexported fields and TS has a private constructor specifically to push you toward the factory functions.
See also