Evaluation
Sometimes the SDK's typed verbs aren't quite the right shape — you
want a value out of the page, a custom predicate, or a one-off DOM
query that doesn't deserve its own helper. Evaluate runs an
arbitrary JavaScript expression in the page and gives you back either
a regular value or a reference to a DOM element you can act on. Running
the same expression inside any frame on the page — even a cross-origin
one — is EvaluateIn with the frame as its first argument.
Evaluate(expr)runs JavaScript in the main document,EvaluateIn(container, expr)runs it in a frame — named by its iframe element, its URL or its name.- The return splits two ways: non-Element values land in
Value(JSON-decoded); a DOM Element populatesRef/IsVisible/Boundsinstead, and theRefgoes straight into a typed follow-up action. - A promise is waited for:
fetch(...).then(r => r.json())comes back as the data, andawaitworks inside the expression.EvaluateWithsets how long, or starts the work without waiting. - Cross-origin frames are first-class — evaluating in one is a single call with the same container a locator's
Intakes. The result'sFramesays where the expression ran. - Don't use
Evaluateas a wait loop.Waitis the right tool for "wait until something is true". - Don't use it to read page state either. URL, title, scroll offset, live input values, checkbox state and duplicate-id warnings all come back from one
GetObservation.
The basic call
A single expression goes in, the JSON-serialised result comes out:
r, err := page.Evaluate(ctx, "document.title")
if err != nil {
log.Fatal(err)
}
fmt.Println(r.Value) // → "Example Domain"const r = await browser.evaluate<string>("document.title");
console.log(r.value); // → "Example Domain"A couple of small but important rules:
- The string you pass must be a single expression, not a script body. For anything multi-statement, wrap it in an IIFE — see the recipes below.
- An expression that answers with a promise is waited for, and the result is what the promise resolved to — see Promises and await.
- The result is whatever your expression evaluates to, JSON-serialised
by the server and parsed back client-side. Anything not
JSON-representable (functions,
undefined, circular structures…) comes back as the zero value. - In TypeScript,
evaluateis generic:evaluate<MyType>(...)lets you type the return value at the call site instead of casting later.
The two return-value shapes
There is only one EvaluateResult type, but it has two distinct
populated shapes depending on what your expression returned:
- Value path — the expression returned a JSON-serialisable value
(string, number, array, plain object).
Valuecarries it; the Element fields stay zeroed. - Element path — the expression returned a single DOM Element.
Valueis empty/null, butRefis a reference to that element, withIsVisibleandBoundspopulated as a bonus.
Either way, Frame says which frame the expression ran in.
The Element path is the part most people miss the first time — and
it's exactly what makes Evaluate a serious tool rather than a
debug helper. It lets you write one expression that finds the
element and hand the result to a typed SDK action with no second
lookup:
// Find the first visible "Add to cart" button via JS, then click it.
r, err := page.Evaluate(ctx, `
[...document.querySelectorAll("button")]
.find(b => b.offsetParent && /add to cart/i.test(b.textContent))
`)
if err != nil || r.Ref == nil {
log.Fatal("no add-to-cart button")
}
_, _ = page.Click(ctx, r.Ref)// Find the first visible "Add to cart" button via JS, then click it.
const r = await page.evaluate(`
[...document.querySelectorAll("button")]
.find(b => b.offsetParent && /add to cart/i.test(b.textContent))
`);
if (!r.ref) throw new Error("no add-to-cart button");
await page.click(r.ref);The pattern — one expression to locate, one typed call to act — is
the same one Wait gives you with
r.Element.Ref. Evaluate just lets you swap CSS for arbitrary
JavaScript when CSS isn't expressive enough.
A quick mental rule: if your expression's last value is an
Element, you'll be looking at the Element path. Anything else (text,
number, plain object, array, null) takes the Value path.
EvaluateIn — same call, any frame
EvaluateIn is Evaluate plus a container. Same return shape, same
rules — the JS just runs in the document the container leads to
instead of the main one:
// The frame, named by its iframe element…
pay := browserscale.CSS("iframe[title='Secure payment']")
title, _ := page.EvaluateIn(ctx, pay, "document.title")
fmt.Println(title.Value, title.Frame.URL)
// …or by the URL it shows.
widget := browserscale.FrameURL("*widget.example.com/*")
ready, _ := page.EvaluateIn(ctx, widget, "window.__widgetReady === true")// The frame, named by its iframe element…
const pay = css("iframe[title='Secure payment']");
const title = await page.evaluateIn<string>(pay, "document.title");
console.log(title.value, title.frame.url);
// …or by the URL it shows.
const widget = frameUrl("*widget.example.com/*");
const ready = await page.evaluateIn<boolean>(widget, "window.__widgetReady === true");The container is what a locator's In takes: an iframe element (by
selector, expression or reference), FrameURL, FrameName,
FrameByID, or a chain of them for a frame inside a frame.
Same-origin or cross-origin, the call shape doesn't change. See
Frames & iframes for all of them.
Unlike an action, EvaluateIn does not wait: a container that is not
on the page fails the call with container_not_found, naming the
missing link. If the frame may still be loading, wait for something
inside it first.
An element as the container
A container that is not an iframe does not change which document the
expression runs in — it runs in that element's document — but hands
the element to the expression as __wrc.scope. That is how an
expression reaches into a component, shadow tree included:
picker := browserscale.CSS("date-picker") // a custom element with a shadow tree
month, _ := page.EvaluateIn(ctx, picker, "__wrc.scope.getAttribute('data-month')")
fmt.Println(month.Value)const picker = css("date-picker"); // a custom element with a shadow tree
const month = await page.evaluateIn<string>(picker, "__wrc.scope.getAttribute('data-month')");
console.log(month.value);An element the expression returns has to lie inside that scope;
otherwise the call fails with outside_scope rather than handing back
a reference to something the container was meant to exclude.
Promises and await
Much of what a page knows it only knows after asking: a fetch to its
own API, a value from IndexedDB, a library call that returns a promise.
Evaluate waits for it. When the expression answers with a promise,
the call returns once the promise has settled, with the value it
resolved to:
// Ask the page's own API, with the page's cookies and origin.
items, err := page.Evaluate(ctx, "fetch('/api/items?page=2').then(r => r.json())")
if err != nil {
log.Fatal(err)
}
fmt.Println(items.Value)// Ask the page's own API, with the page's cookies and origin.
const items = await page.evaluate<Item[]>("fetch('/api/items?page=2').then(r => r.json())");
console.log(items.value);await works inside the expression as well. The expression then runs
as the body of an async function: a single expression is the value,
several statements end with return.
// One expression: its value is the result.
n, _ := page.Evaluate(ctx, "(await (await fetch('/api/items')).json()).length")
// Several statements: return says what comes back.
names, _ := page.Evaluate(ctx, `
const res = await fetch("/api/items");
const items = await res.json();
return items.map(i => i.name);
`)// One expression: its value is the result.
const n = await page.evaluate<number>("(await (await fetch('/api/items')).json()).length");
// Several statements: return says what comes back.
const names = await page.evaluate<string[]>(`
const res = await fetch("/api/items");
const items = await res.json();
return items.map(i => i.name);
`);A promise that is rejected fails the call the way a thrown exception
does: with the code threw and the reason as the message.
The page notices nothing of this. The promise is watched without subscribing to it, and what the expression throws, or a rejection nobody in the page handles, is not reported to the page's own error handling.
How long, and not at all
The wait ends after 30 seconds with the code timeout. The promise
itself goes on in the page — only the call stopped waiting — so running
the same expression again would start its work a second time.
EvaluateWith (in TypeScript the second argument of evaluate)
sets another time:
report, err := page.EvaluateWith(ctx, "buildReport()", browserscale.EvaluateOpts{
TimeoutMs: 120000,
})
var ce *browserscale.CommandError
if errors.As(err, &ce) && ce.Code == "timeout" {
// still running in the page
}try {
const report = await page.evaluate("buildReport()", { timeoutMs: 120_000 });
} catch (e) {
if (e instanceof CommandError && e.code === "timeout") {
// still running in the page
}
}For work that should run while your script does something else, start
it with NoAwait and keep the promise where the page can find it
again. The call returns at once, without a value; evaluating the
variable later waits for it like for any promise:
// Start it; this returns immediately.
_, _ = page.EvaluateWith(ctx, "window.job = crawl(urls)", browserscale.EvaluateOpts{NoAwait: true})
// ... other steps ...
// Come back to it.
rows, err := page.EvaluateWith(ctx, "window.job", browserscale.EvaluateOpts{TimeoutMs: 300000})// Start it; this returns immediately.
await page.evaluate("window.job = crawl(urls)", { noAwait: true });
// ... other steps ...
// Come back to it.
const rows = await page.evaluate("window.job", { timeoutMs: 300_000 });EvaluateOpts also takes the container, as In, so one call can say
where the expression runs and how long it may take; EvaluateIn is the
short form for the container alone.
If the page navigates or reloads while an expression is still waiting,
the call fails with document_gone: the document the promise lived in
is no longer there, and what the expression started may not have
finished.
The canonical pattern: find it anywhere, evaluate where it was
A CSS wait covers every frame, and its result tells you which frame
matched. EvaluateIn then runs your JS in that exact frame:
// 1. Wait for the consent button to appear, anywhere on the page.
r, err := page.Wait(ctx, browserscale.CSS("button.accept-all"))
if err != nil {
log.Fatal(err)
}
// 2. Inspect or transform something in *that* frame.
frame := browserscale.FrameByID(r.Element.Frame.ID)
info, _ := page.EvaluateIn(ctx, frame, `
(() => {
const btn = document.querySelector("button.accept-all");
return { text: btn.textContent.trim(), href: location.href };
})()
`)
fmt.Println(info.Value)
// 3. Or just click it — Wait already gave you its reference.
_, _ = page.Click(ctx, r.Element.Ref)// 1. Wait for the consent button to appear, anywhere on the page.
const { element: el } = await page.wait(css("button.accept-all"));
// 2. Inspect or transform something in *that* frame.
const info = await page.evaluateIn<{ text: string; href: string }>(
frameById(el.frame.id),
`(() => {
const btn = document.querySelector("button.accept-all");
return { text: btn.textContent.trim(), href: location.href };
})()`,
);
console.log(info.value);
// 3. Or just click it — wait already gave you its reference.
await page.click(el.ref!);Three things worth pulling out of that snippet:
- A
CSSwait withoutInis how you say "I don't know where this element lives, find it for me". The match wins and you get the frame back inElement.Frame. EvaluateInalways runs in exactly one document, so it does not takeAnyFrame(). TheWait → EvaluateInhandshake is the cross-frame search pattern. (AJSwait condition does takeAnyFrame(): it is asked in every frame until one answers.)- Note the IIFE wrapping the multi-statement body. Plain
const btn = …; return …;would fail; an arrow IIFE makes it a single expression.
Anti-patterns
Two ways people abuse Evaluate that you should not:
Don't use it as a wait loop
If you find yourself writing setTimeout / polling loops inside an
Evaluate expression, or repeatedly calling Evaluate from your
script to check for some condition, stop. That's Wait's job. See
Waiting for the explicit pattern.
// ❌ Don't do this — burns round-trips and never times out cleanly.
for {
r, _ := page.Evaluate(ctx, "!!document.querySelector('.done')")
if v, ok := r.Value.(bool); ok && v { break }
time.Sleep(100 * time.Millisecond)
}
// ✅ Do this instead.
_, _ = page.Wait(ctx, browserscale.CSS(".done"))// ❌ Don't do this — burns round-trips and never times out cleanly.
while (true) {
const r = await browser.evaluate<boolean>("!!document.querySelector('.done')");
if (r.value === true) break;
await sleep(100);
}
// ✅ Do this instead.
await page.wait(css(".done"));Don't use it for actions the SDK already has
Evaluate("document.querySelector('button').click()") will fire a
click event in the DOM, but it dispatches synthetic JS events with no
real mouse path, no scroll-into-view, no focus management — and modern
anti-bot stacks have been trained to spot exactly that. The same goes
for assigning .value instead of typing: the events the page listens
for never fire. Use Click and
Fill when you mean click and type,
InsertText for a silent bulk paste, and Evaluate for things the SDK
doesn't have a verb for.
Don't use it to re-read page state
Reaching for document.title, location.href, document.body.innerText
or a hand-rolled querySelectorAll('input') map after every step is the
most common way to burn tokens. One
GetObservation already returns the URL, title
and scroll offset in its frame headers, plus every visible control with
its live value, checked state and duplicate-id flags — for a fraction
of what re-deriving it costs.
Where Evaluate genuinely earns its keep alongside an observation is
the opposite direction: verifying a target before you commit to it.
Run the exact expression you plan to pass as a JS(...) locator and
confirm it resolves to one element, and the selector you write into your
script is one you've already proven.
// Prove the anchor is unique before baking it into the script.
n, _ := page.Evaluate(ctx, "document.querySelectorAll('input[name=loginId]').length")
fmt.Println(n.Value) // → 1// Prove the anchor is unique before baking it into the script.
const n = await browser.evaluate<number>("document.querySelectorAll('input[name=loginId]').length");
console.log(n.value); // → 1Gotchas
- Single expression only. Multi-statement bodies need an IIFE:
(() => { /* statements */; return value; })(). undefined, functions and circular structures don't serialise. They come back as the zero value (nilin Go,nullin TS).- Element returns reset the Value field. When
Refis set,Valueisnil/nullregardless of what other properties the element had. Read fromRef/IsVisible/Boundsinstead. - Errors thrown in the expression surface as call errors.
throw new Error("nope")becomes a returned error on the SDK call — there's no separate "expression threw" channel. A rejected promise is the same error. - Statements with
awaitneed areturn. Without one the result is empty, as with any function that returns nothing. - A timeout doesn't stop the work. The promise goes on in the page; running the expression again starts it twice.
- Only real promises are waited for. An object that merely has a
thenmethod is returned as the value it is. - A wait condition is a test, not a call. A
JScondition that answers with a promise is not waited for — a promise is an object, so the condition holds at once. EvaluateIndoesn't takeAnyFrame(). Find the frame withWait, run the JS withEvaluateIn— one frame at a time.EvaluateIndoesn't wait for its container. A frame that is not there fails the call withcontainer_not_found.
- Reading the page — when you want to look at the page without running JS.
- Frames & iframes — every kind of container and how they nest.
- Targeting elements — references, which turn an
Evaluateresult into the next call's target. - API reference: Go
Evaluate/EvaluateIn/EvaluateWith· TSevaluate/evaluateIn.