Support for fetching or setting the active page
The Stagehand libraries in other languages seem to have support for fetching the currently active page: https://docs.stagehand.dev/v3/references/context#activepage
Is there an easy way to support this in Rust, or any workarounds to find out (or change) the currently active page for Stagehand, especially in multi-tab scenarios such as clicking a link that opens on a different tab?
Setting the foreground page is easy, you just have to call page.bring_to_front() or page.activate().
In rust with chromiumoxide that looks something like:
let pages = browser.pages().await?;
let page = if pages.is_empty() {
browser.new_page("about:blank").await?
} else {
pages.into_iter().next().unwrap() // most recently opened tab
};
page.bring_to_front()
// OR
// page.activate().await?;
// OR
// page.execute(ActivateTargetParams::builder().target_id(page.target_id()).build()?).await?;
- https://docs.rs/chromiumoxide/latest/chromiumoxide/page/struct.Page.html#method.bring_to_front OR https://docs.rs/chromiumoxide/latest/chromiumoxide/page/struct.Page.html#method.activate
- https://github.com/browserbase/stagehand-rust/blob/main/examples/chromiumoxide_page_example.rs
- https://docs.rs/chromiumoxide/latest/chromiumoxide/cdp/browser_protocol/target/struct.ActivateTargetParams.html
Unfortunately getting the current foreground page is a hard problem, CDP doesn't have any API to detect which tab is in the foreground. We don't yet expose an easy way to do this via the rust SDK, so you have to keep track yourself of which Target ID / Frame ID you want to control. One option is to try and attach event listeners to every page or to the browser context and listen for load / focus / keyboard / mouse events.