Reading the page
Sometimes a script needs to look at the page rather than change it — to feed an LLM the current state, diff a layout between two snapshots, figure out what's under a coordinate, or read back what the user highlighted. browserscale ships a small set of read-only methods for exactly that. They all return data and never poke the page.
GetObservationis the easy on-ramp: a compact, agent-friendly view of what's visible right now — headers included, so it also answers "where am I?".GetDOMis the full CDP DOM tree as JSON — use when you need every node, not when you need a quick overview.GetDOMHashis a 16-char fingerprint of the DOM tree — pair it withGetDOMto skip unchanged snapshots.InspectAtPosition,HighlightandGetSelectioncover the live-UI cases: hit-test, debug overlay, copy what's selected.- Reading methods don't wait. Pair them with
Waitwhenever you depend on something specific being there.
GetObservation — the agent-friendly summary
The first thing to reach for on an unfamiliar page, and the cheapest way to re-read the current state afterwards. The server walks every frame, keeps what is actually visible, and returns it as text meant to be handed to a model unchanged.
obs, err := page.GetObservation(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(obs)const obs = await page.getObservation();
console.log(obs);Each frame opens with header lines, then emits one line per element, indented by tree depth:
# frame 8F03BF2EEB5ADC9CE47B15775289BBD3 https://example.com/register
# ref @9F2C41D0A1B24C7E8F3A5D6B7C8E9F01
# title "Account registration"
# scroll y=1200/8400
h1[40] "Create your account"
input#email[47] type="email" name="loginId" value="a@b.com" autocomplete="email" required click "E-Mail"
input#agree[51] type="checkbox" checked="false" required click "Accept terms"
select#pref[62] name="prefecture" value="13" options="47" click "Prefecture"
option[63] value="01" "Hokkaido"
option[64] value="02" "Aomori"
…
button[112] type="submit" click "Continue"
Because the headers already carry the URL, the title and the scroll
offset, you rarely need an Evaluate round-trip just to work out where
a flow ended up. The title line is omitted when the document has none,
the scroll line when the frame doesn't scroll.
The # ref line is what turns a row into something you can act on: a
row's number followed by that suffix is the element's
reference. input#email[47] under
# ref @9F2C… is 47@9F2C…, and an action takes it as it is, with no
frame named — see Choosing what to target.
Reading a line
The leading token is tag#id[number], followed by attributes as
key="value", then bare flags, then the quoted text. The number
identifies the element within its frame's section.
| Attribute | What it says |
|---|---|
role, type, name, placeholder | As set on the element. |
value | What a control holds right now. On password fields a length, e.g. value="(8 chars)". On a slider, progress bar or meter built from other elements, where it stands. |
min, max, step | The range of a number, date, time or range field, and of a custom slider or spin button. |
checked | The live state of a checkbox or radio, native or custom. |
expanded, pressed | Whether a menu, accordion or <details> is open, and whether a toggle button is on. |
options, shown | On a select: how many options it has, and how many of them are listed when that is not all. |
scroll | On an element that scrolls its own content: the part it shows, see below. |
href, src | Where a link goes, what an image or iframe loads. |
size | Width and height of a canvas, video or other embedded media, as size="640x360". |
frameId | On an iframe: the frame whose section follows further down. |
hidden | Why an interactive element cannot be seen, see What gets included. |
aria-label | The element's accessible name, when it says something the text does not. |
autocomplete, data-testid | Anchors that hold across page loads, for the selector you write into a script. |
bounds | Position and size as x,y,w,h, only with IncludeBounds. |
Two details matter more than the rest. value is read live from the
control, so it reflects what was actually typed rather than the initial
markup — which is how you verify a Fill landed. And the trailing
quoted string is always the element's label or text, never its
value or placeholder, so an empty field and a prefilled one stay
distinguishable.
The test id is the first of data-testid, data-test-id, data-test,
data-qa and data-cy that is set. It is shown on interactive elements,
and only when no other element of the document carries the same value,
so a selector on it finds this element and no other.
| Flag | What it says |
|---|---|
click | The element is interactive: a control or link, or it has an interactive role, a tabindex of 0 or more, a click handler or an introduced cursor:pointer — which is how <div onclick> buttons get caught. |
disabled, required, readonly | The state of a control, aria-disabled included. |
selected, current | The chosen option, tab or menu item; the entry of a navigation that stands for the current page. |
invalid | The page marks the field as invalid. |
focused | The element has the keyboard focus. |
modal | A dialog that was opened as modal. |
offscreen | Outside the viewport: scroll before acting. |
inert | In plain sight, but it takes neither clicks nor focus, as everything behind a modal dialog does. |
no-pointer-events | In plain sight, but a click there goes to whatever lies underneath. |
newtab | A link that opens another tab. |
shadow | A web component, and rows below it come from its shadow root. A CSS selector from outside doesn't reach those; go through the host. |
on-top | The element lies over the page, see below. |
id-not-unique, id-not-selectable | The id is duplicated, see Choosing what to target. |
offscreen, inert, no-pointer-events and newtab appear only on
interactive elements.
What gets included
What is listed is what a person can see, plus what can be acted on.
- Not rendered, not listed. An element with
display: none, or inside a closed<details>, is left out with everything in it. - Rendered but unseeable elements get a row only when they are
interactive, with the reason in
hidden:visibility,opacity(their own or an ancestor's),zero-size,clipped(inside a box that is collapsed to nothing and clips its content) orunpositioned(no box on the page). That is deliberate: when a click fails, the reason is in the observation instead of the element having silently vanished from it. A label that drives a checkbox the page hides entirely carriescheckedin the checkbox's place. - Shadow roots, open and closed, are part of the listing. The browser's own internals of a control are not.
- Text is reported exactly once, by the nearest element that has a
row. Inline elements such as
span,bandemhave none unless they carry an id, a role or a click signal, so their words are part of the paragraph, button or link around them. Text that CSS generates (::before,::after) is not included, and a string that was cut short ends in an ellipsis. - An element that shows no words, such as an icon button, is named
by
aria-labelledby, itstitle, or the title of the icon in it. - Generic wrappers with no interactivity signal, no id or role and no own text are omitted, and their children reported at the parent's depth.
<select>options are listed one per line, under theiroptgroupwhere there is one, because you need them to callSelectByValue. On a page the first 60 of a select are listed and its row says so:options="249" shown="60". An observation scoped to the select lists all of them.- Canvas, video, audio,
<object>and<embed>get a row with theirsizewhen they are visible and at least 24 px each way. What they show is not in the observation; that takes aScreenshotorReadCanvas. - A child frame gets a section when its iframe can be seen in the parent document. Hidden and collapsed iframes are left out with everything in them.
When something lies over the page
A dialog, a dimmer or a consent layer changes what every click on the page does. When one is there, the frame's headers say so before the first row:
# on top: div#consent[60] covers 100% of the viewport
The line names what a click would hit in place of the page, the widest
first, and how much of the viewport that is. Each element it names has a
row with the flag on-top, so the listing shows where its buttons are.
The page underneath is still listed in full; it just can't be reached
until what is on top is dealt with. A banner along an edge, which leaves
the page usable, is not reported.
Scrolling inside the page
An element that scrolls its own content gets a row, whatever else it is, with the part of that content it shows, per axis that scrolls, in CSS pixels:
div#results[88] scroll="y=1200-1800/8400"
That reads "shows 1200 to 1800 of 8400". A list that loads more when it
is scrolled to its end, a chat log or a table body is found that way;
ScrollTo and the mouse wheel take the element.
Budgets
The limit that normally binds is maxTotalTokens (default 8000),
a budget across all frames measured in estimated tokens rather than
characters — the same character count is worth roughly four times as
many tokens in CJK text as in ASCII, so a character limit would mean
something different on every page. Frames are visited in tree order and
each gets whatever is left, so a page full of iframes can't multiply the
limit.
A long main document does not push the frames out, though: the consent,
captcha, login or payment frame further down is often the one you came
for. A reserve on top of the budget, a quarter of it and at most 2000
tokens, is kept for child frames. Once the budget is spent, the frames
still to come are taken by how much of the viewport their iframe
covers, each with a small share, until the reserve is gone. If frames
are dropped after that, the last line says how many:
# 2 further frame(s) omitted: token budget spent.
maxElementsPerFrame (default 800) is a safety net against runaway
documents, and maxTextLength (default 300) caps human-readable
strings; identifier-like attributes such as type and name have their
own shorter cap and are unaffected.
Running out of budget does not cut the walk off in document order — that
would reliably drop the end of the page and with it the submit button.
Instead the remainder of the frame degrades to what can be acted on:
interactive elements, the headings that say which section they are in,
iframes, elements that scroll and what lies on top of the page. A
# budget spent line stands where that begins, so everything above it
is complete and everything below it is not.
A layer on top usually sits at the very end of the document, where a long page has already run out of budget. Its rows are therefore listed past the budget, from an allowance of their own.
The budget is thus where a frame starts leaving things out, not the size
of the result. A frame goes on with what can be acted on until one and a
half times its budget, where a # truncated: token_budget line ends it,
and what is on top and the frame reserve come on top of that. The most a
result can come to is about twice maxTotalTokens, on a page that has
all of that to show.
When you see # budget spent and still need the rest, raise the budget,
scope the look to the part you work on, or
narrow it to the viewport:
// Just what's on screen right now.
obs, _ := page.GetObservationWith(ctx, browserscale.ObservationOpts{
ViewportOnly: true,
})// Just what's on screen right now.
const obs = await page.getObservation({ viewportOnly: true });Scoping to a subtree
Leave Scope unset for the whole page (the default). After the first
full look, set it to observe only a part — follow-up looks at a form
then cost the form, not the ads around it. The scope is a locator like
any other:
- an element (
CSS,JS, or a reference from the previous observation) scopes to that element's subtree, and can itself be confined with.In(...); - a frame (
FrameURL,FrameName,FrameByID,MainFrame) scopes to that frame's document.
Child iframes reached inside the scope are still visited (so a
checkout form keeps its payment iframe); frames outside the scope are
not. Text mode marks a scoped result with a # scope tag[number]
header line.
Whether something in the scope can be seen is judged as on the whole
page. A scope inside a container that is transparent or collapsed
therefore lists its interactive elements as hidden and nothing else.
// Re-read just the registration form.
obs, _ := page.GetObservationWith(ctx, browserscale.ObservationOpts{
Scope: browserscale.CSS("form#register"),
})
// Or by a reference from the previous observation:
obs, _ = page.GetObservationWith(ctx, browserscale.ObservationOpts{
Scope: browserscale.Ref("120@9F2C41D0A1B24C7E8F3A5D6B7C8E9F01"),
})
// Or one frame:
obs, _ = page.GetObservationWith(ctx, browserscale.ObservationOpts{
Scope: browserscale.FrameURL("*checkout.example.com/*"),
})// Re-read just the registration form.
const obs = await page.getObservation({ scope: css("form#register") });
// Or by a reference from the previous observation:
const again = await page.getObservation({
scope: ref("120@9F2C41D0A1B24C7E8F3A5D6B7C8E9F01"),
});
// Or one frame:
const checkout = await page.getObservation({ scope: frameUrl("*checkout.example.com/*") });Choosing what to target
A row's number with its frame's # ref suffix — 47@9F2C… for
input#email[47] — is the element's reference. Pass it straight to an
action and you never guess a selector, nor name the frame the element
is in:
_, _ = page.Click(ctx, browserscale.Ref("47@9F2C41D0A1B24C7E8F3A5D6B7C8E9F01"))await page.click(ref("47@9F2C41D0A1B24C7E8F3A5D6B7C8E9F01"));It does not survive a new document, though — a call given it after a
navigation fails with a StaleRefError rather than acting on something
else — so it is worthless in a script you intend to run again. Prefer the anchor you can still use
tomorrow: name, then an id flagged with neither id-not-unique nor
id-not-selectable, then a label or text relation — and never a
generated class name. The two id flags are worth internalising:
id-not-unique means the id is duplicated in this tree scope and #id
happens to resolve to this element, while id-not-selectable means it
resolves to a different one, so the element can't be reached by its id
at all.
The moment the observation is in front of you is the only one where
name, the id flags and the label are all visible at once, so pick the
durable target then rather than later. Acting through it right away has
a second payoff: every call that worked during exploration is already a
line of your script, and since actions return the reference of the
element they resolved to, comparing that against the observation proves
the anchor hits the element you meant.
The JSON form
Passing format: "json" returns the same rows with explicit keys. Each
frame carries its document (the suffix of its references), its
element counts, onTop (the row numbers of what lies over the page) with onTopPercent, a degraded flag with
degradedAt (the index of the first element past the budget) and a
truncated reason (max_elements, node_budget or token_budget).
The top-level counts sum that up across frames, with tokensUsed and
framesSkippedForBudget among them. It is roughly twice the size of the
text form for identical information, so it is meant for programmatic
consumers — feed the text form to a model.
obs, _ := page.GetObservationWith(ctx, browserscale.ObservationOpts{
Format: "json",
})
var parsed Observation
_ = json.Unmarshal([]byte(obs), &parsed)const obs = await page.getObservation({ format: "json" });
const parsed = JSON.parse(obs);GetDOM — the full CDP tree
When the observation isn't enough — you need every node, the
nesting, the full attributes — switch to GetDOM. The payload is a
JSON string in standard CDP DOM.Node shape, with same-origin
<iframe> / <frame> / <object> children inlined into the same
tree. Cross-origin frames stop the tree; call GetDOM again with
that frame's frameId to descend.
It is a snapshot, and the inlining is a one-time copy. A live DOM
mirror gives you the same DOM.Node shape
as one tree that stays current across every frame, cross-origin ones
included, with no per-frame recursion on your side.
// Full tree of the main frame.
domJson, err := page.GetDOM(ctx, "", -1)
if err != nil {
log.Fatal(err)
}
// domJson is a CDP DOM.Node tree — feed it into anything that speaks CDP.// Full tree of the main frame.
const { dom } = await page.getDOM();
// dom is a CDP DOM.Node tree — feed it into anything that speaks CDP.The return shape differs across the two SDKs in one cosmetic way: Go
gives you the JSON string directly, TypeScript wraps it in a
{ dom, hash } object where hash is reserved for future use and is
not populated by this call. Either way, when you want the
fingerprint, call GetDOMHash.
Two parameters tune the call:
frameId(Go: positional, TS: positional) — empty / omitted targets the main frame. Use a specific frame's id, fromFramesor a result'sFrame, to descend into a cross-origin frame.depth(Go: positional, TS:opts.depth) —-1for the full tree,0for the root only,Nfor the root plus N descendant levels.
// Just the top two levels — cheap probe before pulling the whole thing.
shallow, _ := page.GetDOM(ctx, "", 2)// Just the top two levels — cheap probe before pulling the whole thing.
const { dom } = await page.getDOM("", { depth: 2 });GetDOMHash — the change detector
GetDOMHash returns the first 8 bytes of sha256(dom) as a 16-char
hex string. Computing it on the server is much cheaper than
transferring the full tree, so it answers "is the content still
identical to what I saw?" without a download.
Two better options exist for the questions people usually ask it,
though. For "did this document move since I last asked?" prefer
GetDomRevision:
a hash has to serialize the whole tree to compute one, while a
revision is a counter the browser already keeps, so it is O(1). And if
you want to follow the page rather than poll it, use a live DOM
mirror — it reports what changed instead of
making you re-fetch and diff.
The loop below still works, and is fine as a one-off check. On a page that changes often it re-serializes the whole document every time the hash moves, which is the cost the mirror exists to avoid:
var lastHash string
for {
hash, err := page.GetDOMHash(ctx, "")
if err != nil {
return err
}
if hash != lastHash {
lastHash = hash
domJson, _ := page.GetDOM(ctx, "", -1)
process(domJson)
}
time.Sleep(500 * time.Millisecond)
}let lastHash = "";
while (running) {
const hash = await page.getDOMHash();
if (hash !== lastHash) {
lastHash = hash;
const { dom } = await page.getDOM();
process(dom);
}
await sleep(500);
}Don't reach for this as a wait substitute. If you're trying to wait
for "the page to stop changing", use Wait with a CSS or JS
condition for the actual element you care about — see
Waiting.
InspectAtPosition — what's under (x, y)?
A hit-test at a viewport-relative pixel coordinate, returning the
topmost element under that point. Elements with
pointer-events: none are skipped, so the result is the actual click
target — not the visually-topmost node. This is what the live-UI
hover overlay calls under the hood.
res, err := page.InspectAtPosition(ctx, 200, 300)
if err != nil {
log.Fatal(err)
}
fmt.Println(res.TagName, res.TextContent, res.Frame.URL)
// res.Ref == nil means nothing was found.const r = await page.inspectAtPosition(200, 300);
console.log(r.tagName, r.textContent, r.frame.url);
// r.ref === undefined means nothing was found.The result carries everything you need to act on the element next:
its Ref, the Frame it is in, TagName, trimmed TextContent,
post-scroll IsVisible and the bounding rect. Pass the Ref to
Click or Fill and the action goes to exactly that element. The
node address a DOM mirror goes by
(BackendNodeId, FrameId) is there too.
Typical use cases:
- Stream-based UIs where the user clicks on the video feed and the script needs to translate the click into a real DOM target.
- Coordinate-driven recipes (canvas/captcha tile, HTML5 game)
where you want to verify what's actually there before firing a
Click(at(...)).
Highlight — the debug overlay
The visual companion to InspectAtPosition. Paints a coloured
overlay on top of the element a reference names. The overlay stays
until the next call — pass no reference to clear it.
r, _ := page.InspectAtPosition(ctx, 400, 250)
_ = page.Highlight(ctx, r.Ref)
// ... screenshot or just watch the live stream ...
_ = page.Highlight(ctx, nil) // clear the overlayconst r = await page.inspectAtPosition(400, 250);
await page.highlight(r.ref ?? null);
// ... screenshot or just watch the live stream ...
await page.highlight(null); // clear the overlayAny reference works: what a Wait found, what a Click acted on, a
row of an observation. Pure debugging affordance — Highlight only
paints visuals, it doesn't change the page's behaviour. Use it freely
in development; in production scripts there's usually no reason to
call it.
A tree view built on a DOM mirror holds
node addresses rather than references; HighlightNode(backendNodeId, frameId) takes those directly.
GetSelection — read what's highlighted
Walks every frame and returns the first non-empty text selection it
finds. Returns "" when nothing is selected anywhere. Useful for
"copy what the user highlighted" flows and for tests that exercise
selection-based UI (e.g. "did our right-click translate this text?").
sel, err := page.GetSelection(ctx)
if err != nil {
log.Fatal(err)
}
if sel == "" {
fmt.Println("nothing selected")
} else {
fmt.Println("user selected:", sel)
}const sel = await page.getSelection();
if (sel === "") {
console.log("nothing selected");
} else {
console.log("user selected:", sel);
}When to reach for which
| You want… | Use |
|---|---|
| A short summary an LLM can read | GetObservation |
| Every node and attribute, once | GetDOM |
| The tree, kept up to date as the page changes | A live DOM mirror |
| "Did this document move since I last asked?" | GetDomRevision — O(1) |
| "Is the content still byte-identical?" | GetDOMHash |
| The element under a specific pixel | InspectAtPosition |
| A visual marker on an element while debugging | Highlight |
| The text the user is currently highlighting | GetSelection |
| To wait for something to appear | Not these — use Wait |
Gotchas
- They don't wait. None of these methods polls for an element to
appear. If you call
GetObservationbefore the page has rendered, you get whatever was visible at that instant. UseWaitfirst for the anchor element you care about. - TS
getDOMreturns{ dom, hash }; Go returns just the DOM string. Cosmetic wrapper difference only — in TS thehashfield is reserved for future use and is not populated bygetDOM. CallgetDOMHashexplicitly in both SDKs. - Cross-origin frames stop the DOM tree.
GetDOMinlines same-origin frames but stops at cross-origin ones. Recurse by callingGetDOMagain with that frame'sframeId(look it up viaFrames— covered in Frames & iframes). InspectAtPositionreturns noReffor misses. Treat that as "nothing there" rather than an error.Highlightis sticky. The overlay persists until you call again — make sure your cleanup path clears it (no reference) or your screenshots will keep showing stale highlights.
- Live DOM mirror — the same tree, but followed instead of re-fetched, and one tree across every frame.
- Evaluation — when you need to run JavaScript instead of (or after) reading the structure.
- Waiting — the explicit pause to put in front of any read that depends on a specific element.
- API reference: Go DOM helpers · TS DOM helpers.