How To Handle Multiple Windows Using Selenium WebDriver
In this post, we will see how to handle multiple windows using Selenium WebDriver. In real time, we face many scenarios, where an application throws multiple popups. We can easily achieve this using Windows Handles in Selenium WebDriver. We use ‘Switch To’ method which allows us to switch control from one window to other.
Here is a program which handles multiple windows. Given clear explanation in the comments section within the program itself. Please go through it to understand the flow.
package softwareTestingMaterial; import org.testng.annotations.Test; import java.util.Iterator; import java.util.Set; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class MultipleWindowsClass{ @Test public void testMultipleWindows() throws InterruptedException{ System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir")+"\\src\\test\\java\\drivers\\geckodriver.exe"); // To open browser WebDriver driver=new FirefoxDriver(); // To maximize browser driver.manage().window().maximize(); // To open Naukri website with multiple windows driver.get("http://www.naukri.com/"); // It will return the parent window name as a String String mainWindow=driver.getWindowHandle(); // It returns no. of windows opened by WebDriver and will return Set of Strings Set<String> set =driver.getWindowHandles(); // Using Iterator to iterate with in windows Iterator<String> itr= set.iterator(); while(itr.hasNext()){ String childWindow=itr.next(); // Compare whether the main windows is not equal to child window. If not equal, we will close. if(!mainWindow.equals(childWindow)){ driver.switchTo().window(childWindow); System.out.println(driver.switchTo().window(childWindow).getTitle()); driver.close(); } } // This is to switch to the main window driver.switchTo().window(mainWindow); } }
If you have any queries, please comment below.