Selenium switch focus to tab, which opened after clicking link

To properly switch to the newly opened Tab you need to induce WebDriverWait for the New Tab to render and then through a for() loop you need to iterate through the available WindowHandles and invoke switchTo().window() with the WindowHandle which is not the previous TAB through the following code block :

String first_handle = driver.getWindowHandle();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", tableRow);
new WebDriverWait(driver,5).until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> allHandles = driver.getWindowHandles();
for(String winHandle:allHandles)
{
    if (!first_handle.equalsIgnoreCase(winHandle)
    {
        driver.switchTo().window(winHandle);
    }
}

Leave a Comment