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