Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I close a specific window using Selenium WebDriver with Java?

Tags:

I use Selenium WebDriver. I open the first page then open the second page - perform some action and go back to first page. Before I want to close the second page I use the command driver.close();, but it closes the first page instead of the second. How can I make Selenium to close a specific window?

Part of code

String HandleBefore = driver.getWindowHandle();   driver.findElement(By.xpath("...")).click();  for (String twohandle : driver.getWindowHandles()) {         driver.switchTo().window(twohandle);     }         driver.findElement(By.linkText("001")).click();  driver.close(); 
like image 626
khris Avatar asked Jul 12 '12 09:07

khris


People also ask

Can we use close () and quit together in Selenium?

In Selenium Webdriver, there are two methods to close a browser window, close() and quit() . These methods are often used interchangeably, but they have different functions.

What is the difference between quit () and close () method in Selenium?

quit() : The quit() method quits the driver, closing every associated window. driver. close() : The close() method closes the currently focused window, quitting the driver if the current window is the only open window. If there are no windows open, it will error out.

How do I close parent window in Selenium?

switchTo(). defaultContent(). close(); It will close the parent window and you can continue your execution on child window.

How do you close a child window?

A child window opens as separate window as a tab. Go back to the parent and click “Close child” and the child window closes. Viola!


1 Answers

    String base = driver.getWindowHandle();      Set <String> set = driver.getWindowHandles();      set.remove(base);     assert set.size()==1;      driver.switchTo().window(set.toArray(new String[0]));      driver.close();     driver.switchTo().window(base); 

This works for me...

like image 101
Franz Ebner Avatar answered Oct 14 '22 08:10

Franz Ebner