Srikanth Nakka Srikanth Nakka - 11 months ago 56
Java Question

Closing all opened tabs except the first tab/main tab using webdriver

Can anyone tell me how to close all opened tabs except the first tab/main tab using webdriver?

I tried below, but it is closing all tabs including first tab as well.

public static void closeTabs() {
String wh1=driver.getWindowHandle();
String cwh=null;
new Actions(driver).sendKeys(Keys.CONTROL).sendKeys(Keys.NUMPAD1).perform();
driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL, Keys.TAB);

Please help me.

Answer Source

Get all the window handles then iterate through them, switching webdriver to the new handle, then calling the close method. Obviously skip this for the original handle, then switch back to the remaining handle.

Something like;

    String originalHandle = driver.getWindowHandle();

    //Do something to open new tabs

    for(String handle : driver.getWindowHandles()) {
        if (!handle.equals(originalHandle)) {