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();
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.
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.
switchTo(). defaultContent(). close(); It will close the parent window and you can continue your execution on 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!
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With