Waiting

Pages take time. Network round-trips, JS bundles, animations, third-party widgets, captchas — there is almost always a moment between "I told the browser to do something" and "the page is in the state I need". The job of Wait is to bridge that gap honestly: return the moment what you described holds, tell you which of your conditions it was — or give up with a diagnosis of how close each one came.

TL;DR
  • Wait marks every point where the page has to get somewhere: after a Navigate, after a submit, after any step that loads a new page or view. Wait for the element you need next, with a timeout sized for that step.
  • One condition or several. Race the outcomes a step can have (next page, form error, challenge) and branch on the Index that matched.
  • Conditions are not only elements: Captcha() matches a challenge, Request(url) / Response(url) match network traffic. Mix them freely; the result's Kind says what matched.
  • Requests and responses are events: start the wait before the action that causes them. A wait does not block the page, so it runs alongside Click or SolveCaptcha.
  • The documents a condition concerns report the moment it holds; nothing re-checks on a timer while the page is idle.
  • Default timeout is 30 s. Override per call with Timeout(ms) in Go / { timeoutMs } in TS.
  • Click, Fill and Drag also find their own target, for up to 5 s. That covers an element rendering a moment late, not a page load.
  • On timeout, a WaitError says per condition how far it got: not_found, found_hidden, found_occluded (with the element covering it), pending_steady, or not_seen for a request that never happened.

When to wait

A flow is a series of steps, and between most of them the page has work to do: Navigate returns when the document commits, before the page's JavaScript has built anything; a submitted form goes to a server that may take ten seconds to answer; a single-page app swaps views without navigating at all. Wait is how a script says "this is where the page has to get somewhere, and this is how long it may take".

Three situations call for it:

  • After every Navigate, and every step that changes the page. Wait for the element the next step needs, with a budget that fits the page — a slow sign-up page gets 25 s, not the 5 s an action allows itself.
  • When the next step depends on what happened. After submitting, the page can show the next step, an error, a challenge or a login modal. Pass all of them, get back the one that happened.
  • Before reading. An Evaluate or GetObservation sees the page as it is right now; wait for the state you want to read first.
_, _ = page.Navigate(ctx, "https://signup.example/", 0)

// The page is usable once the email field is there. Give it time.
_, err := page.Wait(ctx, browserscale.CSS("input[name=email]"), browserscale.Timeout(25000))
if err != nil {
  return err // says whether the field never appeared, stayed hidden or was covered
}
_, _ = page.Fill(ctx, browserscale.CSS("input[name=email]"), email)
_, _ = page.Click(ctx, browserscale.CSS("button[type=submit]"))

// Next step, an error, or a challenge. Branch on what happened.
r, err := page.Wait(ctx,
  browserscale.CSS("input[type=password]"), // index 0
  browserscale.CSS(".error-message"),       // index 1
  browserscale.Captcha(),                   // index 2
  browserscale.Timeout(25000),
)

Navigate → Wait → act and act → Wait: you will write these pairs a lot, and they make a flow readable too — every Wait is a place where the page changes.

What actions already do

Click, Fill and Drag do a short wait of their own: they re-locate the target for up to 5 s, scroll it into view, hold until its bounds stop moving and verify the point before pressing. So an element that renders a few frames after the one before it needs nothing extra.

That budget belongs to the action, not to the page. It is short on purpose, so a wrong selector fails fast. For anything that can take longer — a page load, a redirect chain, a server answering a form — put a Wait in front with a timeout for that step. (Fill also takes a TimeoutMs for its own budget; Click's stays at 5 s.) A timed-out Wait also tells you how far the element got, which a click that gave up cannot.

Anatomy of a wait

A Wait call carries two things:

  1. One or more conditions:
    • element conditions — anything CSS(...) or JS(...) produces (references and At are rejected client-side; see the Targeting elements guide for why);
    • Captcha() — a supported challenge appearing on the page;
    • Request(url) / Response(url) — network traffic (see Waiting for network traffic).
  2. A timeout — how long to wait before giving up.

Where a condition is looked for belongs to the condition itself: a selector means the whole page, iframes included, unless .In(...) confines it (see Waiting in a frame below).

Each element condition is handed to the documents it concerns, and each document reports the moment the condition starts holding — so a match usually arrives within a frame or two, and an idle page costs nothing while you wait. The first condition to match wins. The others are abandoned — there is no second-place winner.

The result is a WaitResult:

FieldWhat it tells you
Index / indexPosition of the condition that matched in your input list
Kind / kindWhat matched: element, captcha, request or response
Element / elementThe matched element, for element: Ref, Frame, IsVisible, Bounds
Captcha / captchaThe matched challenge, for captcha: its type and the Frame it is in
Request / requestThe matched request, for request: method, URL, headers, body
Response / responseThe matched response, for response: status, headers, body

Exactly one of Element, Captcha, Request and Response is set, according to Kind; after a captcha match, hand the page to SolveCaptcha. In TypeScript the result is a union: wait with a single condition already returns the narrowed type (wait(css(...)) has element), and after waitAny checking r.kind narrows it.

Index is the most useful field when you use multiple conditions — it's how you know which branch of the race won. More on that in a moment.

A single condition

The shape you'll use 90 % of the time:

r, err := page.Wait(ctx, browserscale.CSS(".checkout-complete"))
if err != nil {
  log.Fatal("checkout never finished:", err)
}
fmt.Println("element bounds:", r.Element.Bounds)

A few things are happening implicitly here:

  • The selector must match an element that is visible (default Visible(true)) and whose bounding rect has been stable for at least 500 ms (default Steady(500)). Both defaults come from the CSS(...) constructor; override per locator if needed (see the Targeting elements guide).
  • The selector is looked for on the whole page: the main document and every iframe, also one that is created while the wait runs. r.Element.Frame says where it was found.
  • The timeout is 30 s — the SDK's DefaultWaitTimeoutMs.

Custom timeout

The timeout is per call, so size it for the step it guards. A sign-up page behind a slow backend or a queue can take well over the default; a toast after a save should be there within seconds, and waiting 30 s for it only makes the failure slow.

// A slow page: give it longer than the default.
_, err := page.Wait(ctx,
  browserscale.CSS("#otp-code"),
  browserscale.Timeout(40000),
)

// A toast: if it is not there in 5 s, it is not coming.
_, err = page.Wait(ctx,
  browserscale.CSS(".toast-saved"),
  browserscale.Timeout(5000),
)

In Go, Timeout(ms) is one of the variadic arguments to Wait. In TypeScript, it lives inside the opts object — { timeoutMs }. There is no separate "no timeout" mode; pick a value you can live with even if the page is broken.

Racing several conditions

The more interesting case is "either A or B should happen — whichever gets there first, that's the answer". browserscale has first-class support for that pattern: pass multiple locators, get back the Index of whichever matched.

Go takes the conditions as variadic arguments to the same Wait function. TypeScript splits it into wait (one condition) and waitAny (many) so the types stay tidy.

r, err := page.Wait(ctx,
  browserscale.CSS(".success"), // index 0
  browserscale.CSS(".error"),   // index 1
  browserscale.Captcha(),       // index 2
  browserscale.Timeout(10000),
)
if err != nil {
  log.Fatal(err)
}
switch r.Index {
case 0:
  fmt.Println("happy path")
case 1:
  fmt.Println("form error — re-fill and retry")
case 2:
  _, _ = page.SolveCaptcha(ctx, 0, 2)
}

A few notes on the race:

  • The first condition to start holding wins; the others are abandoned. The order of conditions in the list does not decide anything.
  • The condition list is open-ended; you can mix CSS, JS, Captcha, Request and Response, with different .Visible(...) / .Steady(...) modifiers per locator. Branch on Index when the position matters, on Kind when the kind does.
  • On timeout you get a typed WaitError and no result. Its conditions array reports, per condition you passed, the last state it reached: not_found (never appeared), found_hidden (rendered but not visible), found_occluded (visible but covered, with the covering element as occluder), pending_steady (there, but still moving) or not_seen (a request or response that never happened). A condition whose container was never there says so in ScopeError (scopeError), naming the missing link. Each needs a different fix, which is why they are reported separately. Go unwraps it with errors.As; TypeScript matches it with instanceof WaitError.

This is also how you handle pages that load progressively: race the final element you actually want against an error toast that means "give up early".

Waiting in a frame

Each condition has its own place to look. Without .In(...) a CSS condition covers the whole page — the main document and every iframe, including frames created while the wait is running, so there is no need to wait for an iframe before waiting for what is in it. A JS condition runs in the main document. .In(...) changes that per condition:

pay := browserscale.CSS("iframe[title='Secure payment']")

r, err := page.Wait(ctx,
  browserscale.CSS("#order-confirmed"),                 // the whole page
  browserscale.CSS(".card-error").In(pay),              // only the payment frame
  browserscale.JS("location.pathname === '/declined'"), // the main document
  browserscale.Captcha(),                               // the whole page
)

The container can be an iframe element, a frame named with FrameURL / FrameName, MainFrame() to keep a selector out of the iframes, AnyFrame() to have an expression asked in every frame, or any other element for its subtree; the Frames & iframes guide goes through them. A container that is not there yet is waited for like the element itself.

Captcha() watches the whole page, since most challenges live in an iframe; Captcha().In(...) confines it like an element condition, and confining one condition changes nothing for the others. Request and Response watch the whole session regardless of frames.

Waiting for network traffic

Request(url) matches the first request whose URL matches the wildcard (* spans any characters); Response(url) matches the response to such a request, once it has fully arrived, body included. Both watch the whole browser session: the page, its frames, and any tab or popup it opens, across navigations.

Unlike an element, a request is an event, not a state. A wait only sees requests issued after it started — there is no looking back. So start the wait first, then do whatever triggers the request, then collect the result. A wait does not hold the page, so an action or SolveCaptcha runs in parallel with it.

// Start the wait, then click; the wait catches the login call.
done := make(chan *browserscale.WaitResult, 1)
go func() {
  r, _ := page.Wait(ctx,
      browserscale.Response("https://example.com/api/login*"),
      browserscale.Timeout(15000),
  )
  done <- r
}()
_, _ = page.Click(ctx, browserscale.CSS("button[type=submit]"))

if r := <-done; r != nil {
  fmt.Println(r.Response.StatusCode, r.Response.Body)
}

Network conditions race like any other. A typical step after a submit: the next page, a challenge, or the server's error redirect — whichever comes first.

r, err := page.Wait(ctx,
  browserscale.CSS("#inbox"),
  browserscale.Captcha(),
  browserscale.Request("https://example.com/error*"),
  browserscale.Timeout(60000),
)
if err != nil {
  return err
}
switch r.Kind {
case browserscale.WaitKindCaptcha:
  _, _ = page.SolveCaptcha(ctx, 0, 2)
case browserscale.WaitKindRequest:
  return fmt.Errorf("rejected: %s", r.Request.Url)
}

.Abort(true) / .abort() keeps the page from getting what it asked for. On a Request, the request is never sent and the page receives an empty 200. On a Response, the page receives an empty 200 instead of the real response — which you still get in the result. The result carries the request or response either way.

// Read a token off the wire without the page ever seeing it.
r, _ := page.Wait(ctx,
  browserscale.Response("https://example.com/api/token*").Abort(true),
)

Each request is handed to one wait only: two waits started on the same pattern take one matching request each. For capturing everything a session sends, see Network.

Using what comes back

For an element match, the WaitResult is more than a "yes it happened" signal. Three fields of its Element are worth keeping in mind:

  • Ref is a reference to the matched element, ready to pass to a follow-up action. That skips looking the selector up again and guarantees you act on the same element the wait matched — in whichever frame it lives, without naming it. It is unset when a JS condition matched with a value that is not an element.
  • Frame tells you where the element was found: the frame's id, the URL of its document and whether it is the main frame.
  • IsVisible reflects the element's visibility at match time. With the default Visible(true) gating, it is always true on success. If you opted out with .Visible(false), it may be false. For non-Element JS truthy values it is always false — there is no element to measure.
r, _ := page.Wait(ctx, browserscale.CSS("button.submit"))
fmt.Println("found in", r.Element.Frame.URL)

// Click the exact element we just matched, wherever it lives.
_, _ = page.Click(ctx, r.Element.Ref)

This wait → act on the returned reference pattern is the cleanest way to avoid a race between "the wait matched element X" and "by the time the click ran, the selector resolved to a different element Y". If the page navigated in between, the click fails with a StaleRefError instead of landing on something else.

Anti-patterns to avoid

  • time.Sleep / setTimeout instead of Wait. Sleeps are fragile (right today, wrong tomorrow) and slow (you always pay the full delay, even when the page was ready in 50 ms). The only place a hard sleep is acceptable is when you genuinely need to give time to something with no observable signal (e.g. a debounce on the page).
  • Manual polling with Evaluate. If you find yourself looping Evaluate("...condition...") with sleeps in between, you've re-implemented Wait — badly. Use JS(...) as a wait condition instead.
  • Letting an action's 5 s cover a page load. Right after a Navigate or a submit, a bare Click works on a fast day and times out on a slow one. Put a Wait with a budget for that step in front. Within a page that is already there, the action's own wait is enough.
  • Pre-emptive Waits on top of explicit results. When you already hold a WaitResult or an ElementResult for an element, you don't need to wait for it again before acting — pass its Ref to the next action directly.
  • 30-minute timeouts. A long timeout doesn't make the page faster, it makes failures slow. Pick a budget for the operation and stick to it; rely on retries at the next layer up.

Cancellation

In Go, the ctx parameter passed to every method is the cancellation channel. A context.Cancel or context.WithTimeout aborts the wait in-flight and returns the context error — useful for wiring a Wait into a larger budget such as an HTTP handler deadline or a job-level shutdown signal.

waitCtx, cancel := context.WithTimeout(ctx, 8*time.Second)
defer cancel()

_, err := page.Wait(waitCtx, browserscale.CSS(".done"))
if errors.Is(err, context.DeadlineExceeded) {
  // Caller budget ran out — bail out, retry later.
}

The server timeout (Timeout(ms) / timeoutMs) and any client-side deadline both cap how long the wait can run. Whichever fires first wins — a 1 s ctx cancel beats a 30 s server timeout, and a 5 s server timeout beats a 30 s ctx. They never combine into something longer than the smaller of the two.

Gotchas

  • A wait is not an action. It does not click, scroll, or otherwise change the page. For something that may or may not appear and just needs dismissing — a cookie banner, a newsletter modal — register a reaction instead of waiting for it.
  • Wait rejects references and At(...) client-side. These two locators don't carry a selector or JS expression for the page to watch. The SDK throws before sending.
  • Captcha, Request and Response are wait-only. They are not locators, so Click(Captcha()) does not compile in Go and does not type-check in TypeScript.
  • Captcha() and auto-solve. While a wait with Captcha() runs on a page, auto-solve leaves that page's challenges alone, so the wait sees them first. And while an auto-solve runs, the wait's timeout stands still.
  • A request wait started after the click can miss it. The request may already be gone by the time the wait starts. Start it first.
  • A JS condition does not search the iframes. It runs in the main document unless it is put in a frame; .In(AnyFrame()) asks every frame.
See also