0

Here is a code snippet from book which I am using to learn Selenium

public class WindowHandlingTest {
WebDriver driver;
@BeforeMethod
public void setup() throws IOException {
     System.setProperty("webdriver.chrome.driver",
             "./src/test/resources/drivers/chromedriver");
     driver = new ChromeDriver();
     driver.get("http://guidebook.seleniumacademy.com/Window.html");
}

@Test
public void handleWindow() {
    String firstWindow = driver.getWindowHandle();
    System.out.println("First Window Handle is: " + firstWindow);
    WebElement link = driver.findElement(By.linkText("Google Search"));
    link.click();
    String secondWindow = driver.getWindowHandle();
    System.out.println("Second Window Handle is: " + secondWindow);
    System.out.println("Number of Window Handles so for: "
            + driver.getWindowHandles().size());

The problem of this code is, that when a new tab is opened, selenium still thinks that the first tab is opened, which makes the results absolutely wrong. Only when I create ArrayList of all windows and refer to specific tab/window by index, the code works as intended. Are there other "correct" ways of managing browser tabs/windows? Is the code from the book is incorrect?

user218649
  • 73
  • 1
  • 8

2 Answers2

0

getWindowHandle() (singular) will get the handle of the currently focused window.

getWindowHandles() ("s") will get handles of all currently open windows/tabs, in order in which they have been opened.

Only when I create ArrayList of all windows and refer to specific tab/window by index, the code works as intended.

Therefore, it think this is the correct approach.

Mate Mrše
  • 7,997
  • 10
  • 40
  • 77
0

After link.click(); you need switch first, then you can handle new tab.

link.click();

ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));

String secondWindow = driver.getWindowHandle();
System.out.println("Second Window Handle is: " + secondWindow);
System.out.println("Number of Window Handles so for: "
                + driver.getWindowHandles().size());
frianH
  • 7,295
  • 6
  • 20
  • 45