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

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


    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...


In Python

default_handle = driver.current_window_handlehandles = list(driver.window_handles)assert len(handles) > 1handles.remove(default_handle)assert len(handles) > 0driver.switch_to_window(handles[0])# do your stuffsdriver.close()driver.switch_to_window(default_handle)


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); }