Skip to content

Commit f677029

Browse files
committed
Improve in_new_tab check to make new tab more robust. Add doctest.
1 parent 377ca50 commit f677029

1 file changed

Lines changed: 38 additions & 5 deletions

File tree

src/webdrivercommands.rs

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1229,21 +1229,54 @@ pub trait WebDriverCommands {
12291229
Ok(response["value"].clone())
12301230
}
12311231

1232-
// Execute the specified function in a new browser tab, closing the tab when complete.
1233-
// The return value will be that of the supplied function, unless an error occurs while
1234-
// opening or closing the tab.
1232+
/// Execute the specified function in a new browser tab, closing the tab when complete.
1233+
/// The return value will be that of the supplied function, unless an error occurs while
1234+
/// opening or closing the tab.
1235+
///
1236+
/// ```rust
1237+
/// # use thirtyfour::prelude::*;
1238+
/// # use thirtyfour::support::block_on;
1239+
/// #
1240+
/// # fn main() -> WebDriverResult<()> {
1241+
/// # block_on(async {
1242+
/// # let caps = DesiredCapabilities::chrome();
1243+
/// # let driver = WebDriver::new("http://localhost:4444/wd/hub", &caps).await?;
1244+
/// # driver.get("http://webappdemo").await?;
1245+
/// # driver.find_element(By::Id("pagetextinput")).await?.click().await?;
1246+
/// # assert_eq!(driver.title().await?, "Demo Web App");
1247+
/// # // Get the current window handle.
1248+
/// # let handle = driver.current_window_handle().await?;
1249+
/// let window_title = driver.in_new_tab(|| async {
1250+
/// driver.get("https://www.google.com").await?;
1251+
/// driver.title().await
1252+
/// }).await?;
1253+
/// # assert_eq!(window_title, "Google");
1254+
/// # assert_eq!(driver.current_window_handle().await?, handle);
1255+
/// # driver.quit().await?;
1256+
/// # Ok(())
1257+
/// # })
1258+
/// # }
1259+
/// ```
12351260
async fn in_new_tab<F, Fut, T>(&self, f: F) -> WebDriverResult<T>
12361261
where
12371262
F: FnOnce() -> Fut + Send,
12381263
Fut: Future<Output = WebDriverResult<T>> + Send,
12391264
T: Send,
12401265
{
1266+
let existing_handles = self.window_handles().await?;
12411267
let handle = self.current_window_handle().await?;
12421268

12431269
// Open new tab.
12441270
self.execute_script(r#"window.open("about:blank", target="_blank");"#).await?;
1245-
let handles = self.window_handles().await?;
1246-
self.switch_to().window(&handles[1]).await?;
1271+
let mut new_handles = self.window_handles().await?;
1272+
new_handles.retain(|h| !existing_handles.contains(h));
1273+
if new_handles.len() != 1 {
1274+
return Err(WebDriverError::NotFound(
1275+
"new tab".to_string(),
1276+
"Unable to find window handle for new tab".to_string(),
1277+
));
1278+
}
1279+
self.switch_to().window(&new_handles[0]).await?;
12471280
let result = f().await;
12481281

12491282
// Close tab.

0 commit comments

Comments
 (0)