Reputation: 759
I have used the below two methods to switch to the tab and close it.But unfortunately, none of them are useful.Please provide alternate methods.
sol1:
public static void switchTab()
{
try{
webDriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.PAGE_DOWN);
webDriver.close();
webDriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.PAGE_DOWN);
}
catch(Exception e){
e.printStackTrace();}
}
}
Here, driver is closing the whole browser instead of closing the tab.
sol2:
public void switchTab(){
try{
ArrayList<String> tabs2 = new ArrayList<String> (webDriver.getWindowHandles());
webDriver.switchTo().window(tabs2.get(1));
webDriver.close();
webDriver.switchTo().window(tabs2.get(0));
}
catch(Exception e){
e.printStackTrace();}
}
This is throwing index out of bounds exception as there is no other window opened.
Upvotes: 0
Views: 8055
Reputation: 21
If Understand correctly then, this will might help put this in function block.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://google.com");
String gettitle = driver.getTitle();
String windowHandel = driver.getWindowHandle();
System.out.println(windowHandel + " " + gettitle);
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"t");
ArrayList tabs = new ArrayList(driver.getWindowHandles());
System.out.println(tabs.size());
driver.switchTo().window((String) tabs.get(0));
gettitle ="";
driver.get("http://bing.com");
gettitle = driver.getTitle();
System.out.println(tabs.get(0).toString() + " " + gettitle);
driver.switchTo().window(windowHandel);
Thread.sleep(3000);
Actions actionObj = new Actions(driver);
actionObj.keyDown(Keys.CONTROL)
.sendKeys(Keys.chord("w"))
.keyUp(Keys.CONTROL)
.perform();
driver.switchTo().defaultContent();
Upvotes: 0
Reputation: 17553
Try below code
String homeWindow = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
//Use Iterator to iterate over windows
Iterator<String> windowIterator = allWindows.iterator();
//Verify next window is available
while(windowIterator.hasNext()){
//Store the Recruiter window id
String childWindow = windowIterator.next();
//Here we will compare if parent window is not equal to child window
if (homeWindow.equals(childWindow)){
driver.switchTo().window(childWindow);
//switch here to your desired window/tab and perform your action
driver.close();
}
Hope it will help you :)
Upvotes: 1