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

Maybe you just have to wait until a second window is created? Maybe selenium checks window handles too fast?

Try with WebDriverWait

Example:

String currentHandle = driver.getWindowHandle();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));

Set<String> allHandles = driver.getWindowHandles();
for (String handle : allHandles) {
    if (!handle.equals(currentHandle)) driver.switchTo().window(handle);
}

If a number of windows will be less or more than 2, TimeoutException will occur.


 **Try this code:**

   public static void switchToNewWindow(WebDriver driver, WebElement 
   causeOfNewWindow) {

    // Get Handles before opening new window
    Set<String> oldHandles = driver.getWindowHandles();

    // Click element to open new Window
    causeOfNewWindow.click();

    // Get Handles after opening new window
    Set<String> newHandles = driver.getWindowHandles();

    for (String handle : newHandles) {

        if (!oldHandles.contains(handle)) {
            driver.switchTo().window(handle);
        }

    }
}