InterviewSolution
| 1. |
What do you understand about window handle in the context of automated testing? How can you handle multiple windows in Selenium? |
|
Answer» Window handle is a one-of-a-kind identifier that contains the addresses of all of the windows. Consider it a window pointer that returns the string value. Each browser will presumably have its own window handle. This window handle function aids in the retrieval of all window handles.
Let us consider an example code to understand better. We will open the website of InterviewBit and then click on all the links available on the web PAGE. Then, we will switch from the parent window to multiple different child windows and then switch back to the parent window at last. package SeleniumPackage;import java.util.Iterator; import java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome.ChromeDriver;public class WindowHandle_Demo { public static void main(String[] args) throws Exception { System.setProperty("webdriver.chrome.driver", "C:\\Users\\user\\Downloads\\selenium\\chromedriver_win32\\chromedriver.exe"); WebDriver driver = NEW ChromeDriver(); driver.manage().window().maximize(); // Loading the website driver.get("http://www.interviewbit.com/"); String parent=driver.getWindowHandle(); // storing the parent window name as a string List<WebElement> links = driver.findElements(By.tagName("a")); // storing the list of all the ELEMENTS having an anchor tag Iterator<WebElement> it = links.iterator(); // Iterating over the list elements one by one and clicking all the links to open new child windows while(it.hasNext()){ it.next().click(); } Set<String> s = driver.getWindowHandles(); // Storing the list of all the child windows Iterator<String> I1= s.iterator(); // Iterating over the list of child windows while(I1.hasNext()) { String child_window=I1.next(); if(!parent.equals(child_window)) { driver.switchTo().window(child_window); System.out.println(driver.switchTo().window(child_window).getTitle()); driver.close(); } } //switch to the parent window driver.switchTo().window(parent); }}In the above code, we open the landing page of interviewbit and then find all the elements having the anchor tag and click them to open multiple child windows. Then, we iterate over each of the child windows and print them as a string. Finally, having traversed over the entire list, we break from the loop and switch back to the parent window. |
|