Road to handle popup window using text in Webdriver

Some times we have not title of pop window so in this case we can identified some unique text (content ) of popup window which is not in other window. Using this text we can switch to pop window. Below are the logic and implemented code.

package com.webdriver.test;

import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.*;

public class HandlePopUP {
     private WebDriver driver;
     private String baseUrl;

     public void setUp() throws Exception {
           driver = new FirefoxDriver();
           baseUrl = "";
          driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

     public void testHandlePopUp() throws Exception {
          driver.get(baseUrl + "/popupwindow/");
          driver.findElement(By.linkText("Example 1")).click();
          //get main window id before switch to popup
          String currentWindowId = driver.getWindowHandle();
          //retrive all windows id
          Set allWindows = driver.getWindowHandles();
          //switch all windows on by one
                    for (String windowId : allWindows) {
                          String text = "";
                          try {
                                //get text of popup window on which we want to switch
                                text = driver.findElement(By.xpath("//a[@title='Contact Me']")).getText();
                             catch(Exception ex){}
                             //check if you get text
                                         //put here your code what you want to perform on popup
                                         //close popup
                               //switch to parent windwo again
      public void tearDown() throws Exception {


  1. One small error-Set allWindows = driver.getWindowHandles();
    should be Set allWindows = driver.getWindowHandles();

  2. A small change-Set allWindows = driver.getWindowHandles(); Instead of Set allWindows = driver.getWindowHandles();


Leave your comments, queries, suggestion I will try to provide solution