'Selenium WebDriver new tab and Navigate

Based on this post, I managed to open a new tab, but when I try to navigate in the new tab, the navigation occurs in the old tab.

I saw that I should use this:

driver.switchTo().window(windowName);

but what is windowName?



Solution 1:[1]

You have to use window handle function here. You asked for a solution in c#. I used java with selenium webdriver. They both would use similar concepts.

Here is a sample working code in java:

    String parentHandle = driver.getWindowHandle(); // get the current window handle
    System.out.println(parentHandle);               //Prints the parent window handle 
    String anchorURL = anchor.getAttribute("href"); //Assuming u are clicking on a link which opens a new browser window
    anchor.click();                                 //Clicking on this window
    for (String winHandle : driver.getWindowHandles()) { //Gets the new window handle
        System.out.println(winHandle);
        driver.switchTo().window(winHandle);        // switch focus of WebDriver to the next found window handle (that's your newly opened window)              
    }
//Now your driver works on the current new handle
//Do some work here.....
//Time to go back to parent window
    driver.close();                                 // close newly opened window when done with it
    driver.switchTo().window(parentHandle);         // switch back to the original window

Hope this helps!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1