Frames & iframes

Pages embed iframes for payment forms, consent banners, chat widgets, maps, captchas and social logins. In browserscale an iframe is not a second world with its own API: a selector is looked for on the whole page, frames included, and the result says where it was found. When you want to say where to look, you put the locator in a container — the iframe element, a frame named by its URL, or any other element — with the same In(...) for all of them.

TL;DR
  • A CSS(...) locator without In searches the whole page: the main document first, then every frame, same-origin or not, at any depth. No frame has to be named to click a button inside an iframe.
  • Every result says where it found its element: Frame (id, URL, whether it is the main frame) and Ref, a reference to that very element for the next call.
  • In(container) confines the search. The container is another locator: an iframe element leads into its document, any other element means its subtree (shadow trees included), FrameURL / FrameName name a frame without its element.
  • Containers nest: FrameURL(inner).In(outer) is a frame inside a frame.
  • A JS(...) locator runs in the main document unless it is put in a frame; AnyFrame() makes it ask every frame.
  • Frames returns the frame tree when you want to see what a page embeds.

The default: the whole page

Most of the time you know what you are after, not which frame it sits in. So a selector is looked for everywhere, and the result tells you where it was:

res, err := page.Click(ctx, browserscale.CSS("button.accept"))
if err != nil {
  log.Fatal(err)
}
fmt.Println(res.Frame.Main, res.Frame.URL)
// false https://consent.example.com/banner

The order is fixed: the main document first, then the frames in the order they appear in their documents, and frames nobody can see (hidden, without a size) last. A page that has the same selector in the main document and in an iframe therefore gets the main document's element.

The same holds for waits, reactions and captcha conditions: a frame that is created while a wait is running is covered from the moment it exists.

A JS(...) locator is the exception. An expression such as location.pathname === '/done' means something different in every frame, so it runs in the main document and only there, unless you say otherwise (see Expressions and frames).

Saying where to look: In

In takes a container and returns a new locator for the same element, confined to that container. What the container means depends on what it finds:

ContainerWhere the element is looked for
a locator that finds an iframe elementin that iframe's document, same-origin or cross-origin
a locator that finds any other elementin its subtree, including its shadow tree, open or closed
FrameURL(pattern)in the frame whose document URL matches
FrameName(name)in the frame with that name
FrameByID(id)in the frame a result or Frames named
MainFrame()in the main document only
AnyFrame()in every frame, one after the other

An iframe by its element

The natural handle on an iframe is the element that embeds it. Keep the container in a variable and reuse it:

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

_, _ = page.Fill(ctx, browserscale.CSS("input[name=cardnumber]").In(pay), card)
_, _ = page.Fill(ctx, browserscale.CSS("input[name=cvc]").In(pay), cvc)
_, _ = page.Click(ctx, browserscale.CSS("button[type=submit]").In(pay))

The iframe element can be found by anything a locator can express: a selector, a JS expression, or a reference from an earlier result.

A frame by URL or name

Widgets from third parties often sit in an iframe with a generated id and no stable attribute, but their URL is always the same. FrameURL names the frame by the document it shows; * spans any characters:

challenge := browserscale.FrameURL("*hcaptcha.com/*frame=checkbox*")
_, _ = page.Click(ctx, browserscale.CSS("#checkbox").In(challenge))

search := browserscale.FrameName("search")
_, _ = page.Fill(ctx, browserscale.CSS("input[name=q]").In(search), "shoes")

The frame is looked for at any depth below the page. When several frames match, one a person can see is preferred over a hidden one.

A frame inside a frame

A container can itself be put in a container, to any depth. Each link is looked for below the one before it:

outer := browserscale.FrameURL("*/_Incapsula_Resource*")
inner := browserscale.FrameURL("*hcaptcha.com/*frame=checkbox*").In(outer)

_, _ = page.Click(ctx, browserscale.CSS("#checkbox").In(inner))

Kinds mix freely: an iframe element inside a frame named by URL, a dialog inside an iframe, a shadow host inside a dialog.

A subtree or a component

A container that is not an iframe confines the search to that element's subtree. For a component with a shadow tree the subtree includes the shadow tree, open or closed, so the host element is the way in:

dialog := browserscale.CSS("[role=dialog]")
_, _ = page.Click(ctx, browserscale.CSS("button.close").In(dialog))

picker := browserscale.CSS("date-picker") // a custom element with a shadow tree
_, _ = page.Click(ctx, browserscale.CSS("button.next").In(picker))

Only the main document

MainFrame() switches the page-wide search off for one locator:

// The page's own button, not the one an embedded widget also has.
_, _ = page.Click(ctx, browserscale.CSS("button.accept").In(browserscale.MainFrame()))

"This has to be a frame"

A container made from a selector is entered as a frame when the element is an iframe and searched as a subtree when it is anything else. That is usually what you want. Where a page might hand you something else under the same selector, wrap the container in Frame: the call then fails with container_not_found, saying the element is not a frame, instead of quietly searching a subtree.

pay := browserscale.Frame(browserscale.CSS("iframe.pay"))
_, err := page.Fill(ctx, browserscale.CSS("input[name=cardnumber]").In(pay), card)

The container is looked up each time

A locator with In is a description, not a handle. The whole chain is resolved anew whenever the call looks for its element, which has two consequences worth knowing:

  • A call that waits also waits for its container. Click, Fill, Wait and reactions keep looking until their timeout, so a payment iframe that is inserted a second after the page loaded needs no extra wait.
  • A container that never shows up is named. The call fails with container_not_found and says which link of the chain was missing: in[0] (frameUrl "*checkout*"): no frame below shows a document with that URL. A wait that times out reports the same per condition, in ScopeError (scopeError in TS).

An iframe that navigates, or is removed and inserted again, is found again by the same locator, because nothing in it refers to one particular document.

What comes back: Frame and Ref

Every result that names an element carries two things:

  • Frame — where the element was found: the frame's id, the URL of its document and whether it is the main frame.
  • Ref — a reference to that very element, ready to use as the target of the next call or as a container.
res, _ := page.Wait(ctx, browserscale.CSS("iframe.widget"))

// The same iframe, as the place to look next.
_, _ = page.Click(ctx, browserscale.CSS("button").In(res.Element.Ref))

// Or the frame an element turned out to be in.
card, _ := page.Wait(ctx, browserscale.CSS("#card"))
fmt.Println(card.Element.Frame.URL)
_, _ = page.Click(ctx, card.Element.Ref)

A reference names its element together with the document it lives in, so no frame is given with it. It stays good while the element is in its document. Once a navigation replaced that document, a call given the reference fails with a StaleRefError that says where the page is now, instead of acting on whatever took the element's place. Targeting elements has the details.

Waiting across frames

Each condition of a Wait has its own place to look, so one race can watch the page, one frame and the URL at once:

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

res, 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
)
if err != nil {
  log.Fatal(err)
}
switch res.Index {
case 0:
  fmt.Println("paid, confirmed in", res.Element.Frame.URL)
case 1:
  fmt.Println("card refused")
}

A captcha condition takes a container the same way: Captcha().In(pay) only reports a challenge inside that frame.

Expressions and frames

An expression runs in one document. Which one follows the same rules:

// The main document.
title, _ := page.Evaluate(ctx, "document.title")

// A frame's document.
pay := browserscale.CSS("iframe[title='Secure payment']")
inner, _ := page.EvaluateIn(ctx, pay, "document.title")
fmt.Println(inner.Value, inner.Frame.URL)

// A JS locator inside a frame.
_, _ = page.Click(ctx, browserscale.JS(
  `[...document.querySelectorAll('button')].find(b => /Pay/.test(b.innerText))`).In(pay))

// A JS locator asked in every frame: the first frame that answers wins.
_, _ = page.Wait(ctx, browserscale.JS(
  `[...document.querySelectorAll('button')].find(b => b.innerText === 'Accept all')`,
).In(browserscale.AnyFrame()))

When the container is an element rather than a frame, the expression runs in that element's document and gets the element as __wrc.scope. Evaluation covers the return values.

Seeing what a page embeds

Frames returns the page's frame tree: the main frame with its children, each with its URL, name, size and whether it can be seen. It is for finding out what would tell one frame from the others, not something a flow needs on its way:

frames, err := page.Frames(ctx)
if err != nil {
  log.Fatal(err)
}
frames.Walk(func(f *browserscale.FrameInfo, depth int) bool {
  fmt.Printf("%s%s name=%q visible=%v\n", strings.Repeat("  ", depth), f.Url, f.Name, f.IsVisible)
  return true
})
// https://shop.example.com/checkout name="" visible=true
//   https://pay.example.com/card name="card" visible=true
//   https://consent.example.com/banner name="" visible=false
FieldWhat it tells you
urlThe URL of the document the frame shows — what FrameURL goes by.
nameThe frame's name — what FrameName goes by.
frameIdThe frame's id, for FrameByID. It stays the same when the frame navigates, but belongs to this session.
isVisiblefalse for a frame that is hidden or has no size.
isLoadingtrue while the frame is navigating. Wait for the element you need rather than polling this.
hasJSContexttrue once the frame can run an expression.
isOOPIFtrue for a frame from another site than its parent. Informational: every call works the same either way.
absoluteRectPosition and size in the page's viewport, however deep the frame is nested.
relativeRectPosition relative to the parent frame.
childrenThe frames embedded in this one.

To act in a frame of the tree straight away, turn it into a container: f.Locator() in Go, frameById(f.frameId) in TypeScript. In anything you write down, prefer the iframe's selector, FrameURL or FrameName: they still hold in the next session.

Reading the page shows the same structure from the other side: an observation lists every frame with its elements, and Scope limits it to one frame or one element.

Coordinates across frames

A frame's absoluteRect is in the page's viewport coordinates, no matter how deep it is nested. A click at a point therefore needs no translation through the frames above it:

frames, _ := page.Frames(ctx)
var widget *browserscale.FrameInfo
frames.Walk(func(f *browserscale.FrameInfo, _ int) bool {
  if strings.Contains(f.Url, "maps.example.com") {
      widget = f
      return false
  }
  return true
})

// The centre of the frame, in the page's viewport.
r := widget.AbsoluteRect
_, _ = page.Click(ctx, browserscale.At(r.X+r.Width/2, r.Y+r.Height/2))

Frames vs. tabs and popups

A frame lives inside a page; a tab or popup is a page of its own. When a click opens a target=_blank link or a window.open popup, you get a second Page with its own frame tree, not a new frame. Pages lists every page with its FrameTree, IsPopup and Opener, so the popup's frames are as reachable as the main page's — act on them through that page's handle. The Page section in Core concepts covers how the focus moves between pages and how to follow it with ContextEvents.

Gotchas

  • The first match in page order wins. Without In, a selector that exists in the main document and in an iframe gets the main document's element. If you mean the one in the frame, say so with In.
  • An expression does not search frames by itself. JS(...) runs in the main document; put it in a frame, or in AnyFrame().
  • At(x, y) and references take no container. A point is a point in the page's viewport, and a reference already names its document.
  • EvaluateIn needs one place. It runs an expression in one document, so AnyFrame() is refused there; use a wait with a JS locator in AnyFrame() to find the frame, then its Frame.
  • A frame id is a session value. It is handy inside a run, and useless in a script that runs tomorrow. Selectors, URLs and names travel.
  • Don't branch on isOOPIF. Whether a frame comes from another site changes nothing about how it is addressed.
See also