Reputation: 11
I am learning Selenium-Webdriver and so for practice working on one scenario, but I'm stuck in step#3. Scenario is as follows:
So far, I'm able to open google home page, perform a search on the word "WebDriver" and open the first two links, but now I'm unable to switch to the second and third tab and close them. My code so far is:
String originalHandle = driver.getWindowHandle();
System.out.println("Before switching title is:" +driver.getTitle());
String selectLinkOpeninNewTab = Keys.chord(Keys.COMMAND,Keys.ENTER);
WebElement link1 = driver.findElement(By.xpath(".//*[@id='rso']/div[2]/div[1]/div/h3/a"));
link1.sendKeys(selectLinkOpeninNewTab);
WebElement link2 = driver.findElement(By.xpath(".//*[@id='rso']/div[2]/div[2]/div/h3/a"));
link2.sendKeys(selectLinkOpeninNewTab);
Set<String> s1 = driver.getWindowHandles();
Iterator<String> i1 = s1.iterator();
int i = 0;
while(i1.hasNext())
{
i++;
String childwindow = i1.next();
if(!originalHandle.equalsIgnoreCase(childwindow))
{
driver.switchTo().window(childwindow);
Thread.sleep(10000);
System.out.println("After switching title of new Tab "+i+ " title is " +driver.getTitle());
driver.close();
}
}
driver.switchTo().window(originalHandle);
System.out.println("Original window tab title is" +driver.getTitle() );
I'm not sure where it's going wrong and how to fix it. :(
Upvotes: 1
Views: 2556
Reputation: 11
http://www.dev2qa.com/open-multiple-windows-tabs-in-selenium-webdriver/
Upvotes: 1
Reputation: 11427
I searched for such functionality as tab switching but found nothing. Closest to this is switch of windows. (there are lot of comments that WindowHandles can be used for tab switching, but this is not true -- I had tried a lot. Its can be used only for windows switch, but not tabs switch)
if you need to open in new window -- you need to click on link with pressed shift btn
code is something like
Actions.KeyDown(Keys.Shift).Click(ElementToClick).KeyUp(Keys.Shift).Build().Perform();
and if you need to switch the window
var _windowsList = new List<String>(Instance.WindowHandles);
Instance.SwitchTo().Window(_windowsList[0]);
Upvotes: 1
Reputation: 761
Please try with the below code:
Set<String> s1 = driver.getWindowHandles();
for(String childwindow : s1) {
if(!originalHandle.equals(childwindow)) {
driver.switchTo().window(childwindow);
System.out.println("Tab title is " + driver.getTitle();
}
driver.close();
}
driver.switchTo().window(originalHandle);
Hope this helps.
Upvotes: 1
Reputation: 32038
Could be too late, but hope this helps :
for (String winHandle : driver.getWindowHandles()) { //Gets the new window handle
System.out.println(winHandle);
driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
Upvotes: 1