3

I came across many solutions for switching between windows, one of them is:

Set<String> allWindows = driver.getWindowHandles();
for(String currentWindow : allWindows){
   driver.switchTo().window(currentWindow);
}

But, I am unable to go to a particular window. Can someone tell me how to switch to 3rd window from parent window (using java client library)?

3

The solution I would use is the WebDriver's driver.switchTo().frame() method but avoiding the index number.

You can select the window you want using;

  1. A number. (0 based index normally but NOT always with IE)
  2. A name or ID.
  3. A previously found WebElement.

An example:

driver.switchTo().frame(driver.findElement(By.id("Head1")));
| improve this answer | |
1
File file = new File("G:\\Selenium\\All_Jars\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver",file.getAbsolutePath() );
driver = new ChromeDriver();

//Maximize the window       
driver.manage().window().maximize();

driver.get("http://www.rediff.com/");

//Get all window handles
Set<String> allHandles = driver.getWindowHandles();

//count the handles Here count is=2
System.out.println("Count of windows:"+allHandles.size());      

//Get current handle or default handle
String currentWindowHandle = allHandles.iterator().next();
System.out.println("currentWindow Handle"+currentWindowHandle);

//Remove first/default Handle
allHandles.remove(allHandles.iterator().next());

//get the last Window Handle
String lastHandle = allHandles.iterator().next();
System.out.println("last window handle"+lastHandle);

//switch to second/last window, because we know there are only two windows 1-parent window 2-other window(ad window)
driver.switchTo().window(lastHandle);
System.out.println(driver.getTitle());
driver.findElement(By.tagName("body")).click();
| improve this answer | |
  • Given the age of this question, it would help if you added an explanation that isn't in your code. Also, your solution will not be particularly reliable unless there are two and only two windows, and does not answer the OPs question of finding a specific window. – Kate Paulk May 21 '15 at 11:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.