Â
Handling multiple windows in Selenium WebDriver involves switching between different windows or tabs that are open in the browser.Â
The main steps to handle multiple windows in Selenium WebDriver with Java:
Storing the handle of the main window: Before opening any new windows, it's important that we store the handle of the main window so that we can switch back to it later. so for that purpose we need to use getWindowHandle()Â in our script.
Opening a new window: This can be done by clicking a link or button that opens a new window driver.findElement(By.xpath()).click;
Storing the handles of all open windows: For storing the handles of multiple windows Selenium provides the getWindowHandles() method to get the handles of all open windows in a set.
Iterating through the set of windows: Using a loop, we can iterate through the set of windows and switch to each one using the switchTo().window() method.
Performing actions on the new window: Once we have switched to the new window, we can perform various actions on it such as interacting with elements or taking screenshots.
Closing the new window: After we have finished interacting with the new window, we can close it using the close() method.
Switching back to the main window: Finally, we can switch back to the main window using the handle stored earlier and close it if necessary.
Below Code for Multiple Window Handling:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
Â
public class MultiWindowTest {
public static void main(String[] args) {
// Initialize the web driver
WebDriver driver = new ChromeDriver();
Â
// Open the first window
driver.get("https://example.com/window1");
Â
// Store the current window handle
String mainWindow = driver.getWindowHandle();
Â
// Open a new window by clicking a link or button
driver.findElement(By.linkText("Open new window")).click();
Â
// Store the handles of all open windows in a set
Set<String> allWindows = driver.getWindowHandles();
Â
// Iterate through the set of windows
for (String window : allWindows) {
if (!window.equals(mainWindow)) {
driver.switchTo().window(window);
// Perform actions on the new window
// ...
// Close the new window
driver.close();
}
}
// Switch back to the main window
driver.switchTo().window(mainWindow);
// Close the main window
driver.close();
}
}
Post a Comment