How do I close a focused window using Selenium WebDriver in Java?

0 votes

I work with Selenium WebDriver. I initially open the first page then move on to the second page and perform some action and go back to the first page. In this case, I want to close the first page and work on the second. I use the command driver.close() to do this, but, it closes the second page instead of the first. 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("abc")).click();
 driver.close();
May 9 in Selenium by Surya
• 950 points
47 views

1 answer to this question.

0 votes

You can use this   

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 is easy and it works for me

Hope this helps

answered May 10 by Vaishnavi
• 1,080 points

Related Questions In Selenium

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to open a browser window in full screen using Selenium WebDriver with C#

Simply Use this: driver.Manage().Window.Maximize(); READ MORE

answered Jun 7, 2018 in Selenium by Samarpit
• 5,130 points
2,593 views
0 votes
1 answer

How do I get current URL in Selenium Webdriver using Python?

Use current_url element. Example: print browser.current_url READ MORE

answered Aug 8, 2018 in Selenium by Meci Matt
• 9,400 points
3,981 views
0 votes
1 answer

Finding WebDriver element with Class Name in java

The better way to handle this element ...READ MORE

answered Apr 10, 2018 in Selenium by nsv999
• 5,050 points
261 views
0 votes
1 answer
0 votes
1 answer

Geo-location microphone camera pop up

To Allow or Block the notification, access using Selenium and you have to ...READ MORE

answered May 11, 2018 in Selenium by Samarpit
• 5,130 points
629 views
0 votes
1 answer

How to use such xpath to find web elements

It's much simpler to use: #MyDiv123 > div.super or ...READ MORE

answered Jun 14, 2018 in Selenium by Samarpit
• 5,130 points
257 views
0 votes
1 answer
0 votes
1 answer

How to auto-refresh the ChromeDriver using Selenium Webdriver?

You can use this command. Also, refresh ...READ MORE

answered May 10 in Selenium by Vaishnavi
• 1,080 points

edited May 10 by Omkar 178 views