I am working with multiple tabs in a browser, but I can’t figure out how to switch from one window/tab to another. How can I correctly handle switching between multiple windows in Selenium WebDriver?
String originalWindow = driver.getWindowHandle();
driver.findElement(By.id("openNewTab")).click();
Set<String> windowHandles = driver.getWindowHandles();
for (String windowHandle : windowHandles) {
if (!windowHandle.equals(originalWindow)) {
driver.switchTo().window(windowHandle);
}
}
I am working with multiple tabs in a browser, but I can’t figure out how to switch from one window/tab to another. How can I correctly handle switching between multiple windows in Selenium WebDriver?
String originalWindow = driver.getWindowHandle();
driver.findElement(By.id("openNewTab")).click();
Set<String> windowHandles = driver.getWindowHandles();
for (String windowHandle : windowHandles) {
if (!windowHandle.equals(originalWindow)) {
driver.switchTo().window(windowHandle);
}
}
Share
Improve this question
edited Nov 19, 2024 at 4:11
Kefi Tech Solutions Pvt Ltd
asked Nov 18, 2024 at 11:54
Kefi Tech Solutions Pvt LtdKefi Tech Solutions Pvt Ltd
112 bronze badges
1
- Can you say what is wrong here? Do you have multiple window handles after "clicking" openNewTab? – matt Commented Nov 18, 2024 at 12:15
1 Answer
Reset to default -1When working with multiple windows in Selenium WebDriver, here’s how you can handle them step by step:
- First, save the original window’s handle using getWindowHandle(). This is important so you can switch back to it later.
- After opening a new window (like by clicking a button that opens a new tab), use getWindowHandles() to get all the currently open window handles.
- Then, use switchTo().window() to switch to the new window.
Here’s a simple example of how the code looks:
//Save the original window handle
String originalWindow = driver.getWindowHandle();
// Open a new window (e.g., by clicking a button)
driver.findElement(By.id("openNewTab")).click();
// Get all window handles
Set<String> windowHandles = driver.getWindowHandles();
// Switch to the new window
for (String windowHandle : windowHandles) {
if (!windowHandle.equals(originalWindow)) {
driver.switchTo().window(windowHandle);
break;
}
}
// Once done with the new window, you can switch back to the original window
driver.switchTo().window(originalWindow);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745619893a4636455.html
评论列表(0条)