Identifying and handling a window by its title

Many a time, developers don't assign the name attribute to windows. In such cases, we can use its window handle attribute. However, the handle attributes keep changing and it becomes difficult to identify the window, especially when there is more than one window open. Using the handle and title attributes of the page displayed in a window, we can build a more reliable way to identify child windows.

In this recipe, we will use the title attribute to identify the window and then perform operations on it.

How to do it...

We will create a test that retrieves the handles of all the open windows in the current driver context. We will iterate through this list and check the title matching the criteria, as follows:

@Test
public void testWindowUsingTitle() {
  // Store WindowHandle of parent browser window
  String parentWindowId = driver.getWindowHandle();

  // Clicking Visit Us Button will open Visit Us Page in a new child
  // window
  driver.findElement(By.id("visitbutton")).click();

  // Get Handles of all the open windows
  // iterate through list and check if tile of
  // each window matches with expected window title
  try {
    for (String windowId : driver.getWindowHandles()) {
      String title = driver.switchTo().window(windowId).getTitle();
      if (title.equals("Visit Us")) {
        assertEquals("Visit Us", driver.getTitle());
        // Close the Visit Us window
        driver.close();
        break;
      }
    }
  } finally {
    // Switch to the parent browser window
    driver.switchTo().window(parentWindowId);
  }

  // Check driver context is in parent browser window
  assertEquals("Build my Car - Configuration", driver.getTitle());
}

How it works...

The driver.getWindowHandles() method returns the handles of all the open windows in a list. We can then iterate through this list and find out the matching window by checking the title of each window using the handle attribute, as follows:

for (String windowId : driver.getWindowHandles()) {
      String title = driver.switchTo().window(windowId).getTitle();
      if (title.equals("Visit Us")) {
        assertEquals("Visit Us", driver.getTitle());
        // Close the Visit Us window
        driver.close();
        break;
      }
    }

Tip

You can create a reusable function for identifying pop-up windows using the title attribute.

See also

  • The Identifying and handling windows recipe
  • The Identifying and handling a window by its content recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.87.161