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

5

27

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();
Corrade answered 12/7, 2012 at 9:46 Comment(3)
does the click happen in the right (second) window?Stench
The code is not very readable. You don't use the stored handleBefore, then you switchTo() to all windows in a loop. I guess that the last switchTo gets you to the first window instead of the second. I recommend you to start over, read the docs once again and read the javadocs of switchTo().Disenfranchise
You have to take the window handles to switch between parent and child window.Crossexamine
S
27
    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...

Stench answered 12/7, 2012 at 10:13 Comment(4)
My code works, just something wrong with sequense of closing windowCorrade
@Khris A Set is of java.util package.Disenfranchise
Franz, I am using intellij and 'driver.switchTo().window(set.toArray(String[0]));' line says 'expression expected' what does that mean?Bareheaded
just enter the new keyword for the Array declaration, edited my answer accordingly, sryStench
M
14

In Python

default_handle = driver.current_window_handle
handles = list(driver.window_handles)
assert len(handles) > 1

handles.remove(default_handle)
assert len(handles) > 0

driver.switch_to_window(handles[0])
# do your stuffs
driver.close()
driver.switch_to_window(default_handle)
Matelda answered 1/3, 2016 at 9:33 Comment(0)
R
2

You can close a specific window by it's title or identifying a specific unique element of that window..

private void SwitchTabandClose()
{
    Set <String> windows = driver.getWindowHandles();
    String mainwindow = driver.getWindowHandle();

    for (String handle: windows)
    {
        driver.switchTo().window(handle);
        System.out.println("switched to "+driver.getTitle()+"  Window");
        String pagetitle = driver.getTitle();
        if(pagetitle.equalsIgnoreCase("XYZ Title"))
        {
            driver.close();
            System.out.println("Closed the  '"+pagetitle+"' Tab now ...");
        }
    }

    driver.switchTo().window(mainwindow);
 }
Reside answered 15/2, 2016 at 14:24 Comment(0)
G
1

Ramnarayan's solution works great. Modified it a bit for reusablity:

public static String switchToWindowByTitle(WebDriver driver, String windowTitle) {
  Set<String> handles = driver.getWindowHandles();
  String currentHandle = driver.getWindowHandle();
  for (String handle : handles) {
    driver.switchTo().window(handle);
    if (windowTitle.equalsIgnoreCase(driver.getTitle())) {
      break;
    }
  }

  return currentHandle;
}


// How to use method
String currentHandle = SeleniumUtil.switchToWindowByTitle(driver, WINDOW_TITLE);
driver.close(); // Close WINDOW_TITLE page or do other things
driver.switchTo().window(currentHandle); // Return to current page
Granulite answered 21/8, 2017 at 17:38 Comment(0)
D
0

Following a little the work of the other post, I have done it like this.

     public static void changeFocusToWindowByTitle(WebDriver driver, String windowTitle) {
        Set<String> handles = driver.getWindowHandles();
        for (String windowHandle : handles) {
            driver.switchTo().window(windowHandle);
            if (windowTitle.equalsIgnoreCase(driver.getTitle())) {
                logger.debug("Focus has been changed to the window: " + driver.getTitle());
                break;
            }
        }
    }

 public static void closeWindow(WebDriver driver, String windowTitle) {
        Set<String> handles = driver.getWindowHandles(); ;
        for (String handle: handles ) {
            driver.switchTo().window(handle);
            if (driver.getTitle().equalsIgnoreCase(windowTitle)) {
                logger.debug("Close window: " + windowTitle);
                driver.close();
                break;
            }
        }
    }
Disreputable answered 13/1, 2023 at 16:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.