Handling Alert dialog, Popup windows and Frames | Handling Popup windows

In the Previous Tutorial, we learned how to handle the Alert window. In this tutorial, we will learn to handle popup windows. We’ll write code to switch over multiple browser windows and perform some actions on them.

As we can see on  Automation Practice page, there is a link Click Me to open New Window. If we click on this link it will open the second window. Now on the second-page window, there is a link β€˜Click Me To Open Third Window’. If you click on this link it will open third-page window.

When a new browser window is opened, doesn’t WebDriver know it needs to perform further actions in the new Window?

WebDriver will continue to refer the parent window until we tell it explicitly – Hey, switch to the window with the given title. Once we do that, it’ll continue to refer to the new window until we remind her – Hey, your job is over. Can you please switch back to the parent window?

Let us first launch the browser and navigate to Automation Practice page:

System.setProperty("webdriver.chrome.driver", "C:\\teachmeselenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://cosmocode.io/automation-practice");
from selenium import webdriver

chrome_driver_path = "C:/teachmeselenium/chromedriver.exe"
driver = webdriver.Chrome(chrome_driver_path)
driver.get("https://cosmocode.io/automation-practice")

What is a Window handle?

Selenium WebDriver assigns every browser window opened by it a unique alphanumeric id. This unique id is called Window Handle. Selenium WebDriver uses Window Handle of a particular window to switch control over it from another window.

Get the current window handle

String strParentWindowHandle = driver.getWindowHandle();
parent_window_handle = driver.current_window_handle
  • Click on the link – Click Me to open New Window
driver.findElement(By.linkText("Click Me to open New Window")).click();
driver.find_element_by_link_text("Click Me to open New Window").click()
  • Before performing any action on the second window we first need to switch to it.
  • In order to switch to any window, we either need its page title or its window handle.

Switch to a browser window by using its Title:

There can be various ways to get the page’s title. The best way is to perform right-click anywhere on the page, select Inspect Element and search for the title tag there.

As we can see the page title is:

<title>Beginner | Automation Practice – 2nd Window – Teach me Selenium</title>
driver.switchTo().window("BROWSER_TITLE_HERE");
driver.switch_to.window("BROWSER_TITLE_HERE")

What if I am not sure what is the page title of a new window? Or if the developer forgets to give the page a title?

We’ll use window handle in this case.

Switch to a browser window by using its Window Handle:

Get the list of all window handles 

Set<String> setOldWindowHandles = driver.getWindowHandles();
old_window_handles = driver.window_handles()

Iterate over the list of Window handles

Let us iterate over this list using a for-loop and compare it with the previously saved window handle. The handle which does not match with the saved one is the new browser handle. We can use this window handle to switch to the new browser window. And finally, we’ll exit from the loop.

//Getting one Window handle each time the loop runs
for(String strWindowHandle: setNewWindowHandles){
    //If this window handle is not found in collection of Old Window handles, it must be the new one
    if(! setOldWindowHandles.contains(strWindowHandle)){
        //Switch to the new window
        driver.switchTo().window(strWindowHandle);
        System.out.println(driver.getTitle());
        //Exit from loop
        break;
    }
}
#Getting one Window handle each time the loop runs
for window_handle in old_window_handles:
    #If this window handle is not found in the collection of Old Window handles,
    #it must be the new one
    if window_handle not in old_window_handles:
        #Switch to the new window
        driver.switch_to.window(window_handle)
        print(driver.title)
        #Exit from loop
        break
  • As we can see there is a drop-down list in the second window. We will try to select a value from the list to make sure that we successfully switched to this window. We will also click on the link Click Me To Open Third Window.
Select lstSecondWindow=new Select(driver.findElement(By.id("list-second-window")));
lstSecondWindow.selectByVisibleText("Second Window");
select = Select(driver.find_element_by_id("list-second-window"))
select.select_by_visible_text("Second Window")
  • Click on the link β€˜Click Me To Open Third Window’.
driver.findElement(By.linkText("Click Me To Open Third Window")).click();
driver.find_element_by_link_text("Click Me To Open Third Window").click()
  • The last line of code will trigger the opening of the third new browser window.
  • We’ll again get the collection of Window handles:
Set<String> setNewWindowHandles = driver.getWindowHandles();
new_window_handles = driver.window_handles()
  • To get the window handle of the latest opened window we need to compare the latest list of window handles new_window_handles with the old one old_window_handles. One that doesn’t match will be the latest window handle. We’ll use it to switch to the new window:
//Getting one Window handle each time the loop runs
for(String strWindowHandle: setNewWindowHandles){
    //If this window handle is not found in collection of Old Window handles, it must be the new one
    if(!setOldWindowHandles.contains(strWindowHandle)){
        //Switch to the new window
        driver.switchTo().window(strWindowHandle);
        System.out.println(driver.getTitle());
        //Exit from loop
        break;
    }
}

The first line of code (starting from for) is saying to start a loop for each String in the Set (or assume it list). So if WebDriver has opened 3 windows, the Set β€˜setNewWindowHandles’ will have 3 Window handles and this loop will iterate (or run) 3 times. Each time it will take 1 Window handle and assign it to String β€˜strWindowHandle’. Now the second line of code (starting from if) will check if the Set of old window handles β€˜setOldWindowHandles’ contains this Window handle β€˜strWindowHandle’. If it contains then as we have used β€˜!’ (Not), the condition will become false and execution will not go inside β€˜if’ and the next iteration of the loop will start. If the condition is true, it means we have got the window handle of the latest window. The execution will go inside β€˜if’ and we will use that window handle to switch to the latest opened window.

#Getting one Window handle each time the loop runs
for window_handle in new_window_handles:
    #If this window handle is not found in the collection of Old Window handles,
    #it must be the new one
    if window_handle not in old_window_handles:
        #Switch to the new window
        driver.switch_to.window(window_handle)
        print(driver.title)
        #Exit from loop
        break

Go back to the parent window

At any time of the execution we can switch over to the first opened window:

driver.switchTo().window(strParentWindowHandle);
// you can also pass null to get back to parent window
driver.switchTo().window(null);
#Get current window handle
parent_window_handle = driver.current_window_handle
#Now perform some task to open another window
#Switch to the new window
#Once done, to switch back to the parent window
driver.switch_to.window(parent_window_handle)

Complete code

System.setProperty("webdriver.chrome.driver", "C:\\teachmeselenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://cosmocode.io/automation-practice/");
//Storing current window's handle
String strFirstWindowHandle = driver.getWindowHandle();
//Clicking on a link that opens a new window
driver.findElement(By.linkText("Click Me to open New Window")).click();
//Storing the collection of all opened windows (in our case it would be 2)
Set<String> setWindowHandles = driver.getWindowHandles();
//Iterating over all windows handles
for(String strWindowHandle: setWindowHandles){
	//If the window handle is not same as the one stored before opening up second window, it is the new window
	if(!strWindowHandle.equals(strFirstWindowHandle)){
		//Switch to the new window
		driver.switchTo().window(strWindowHandle);
		//Print window title
		System.out.println(driver.getTitle());
		//Exit from loop
		break;
	}
}


//Storing current window's handle. In our case it would be second window.
String strSecondWindowHandle = driver.getWindowHandle();
//Select the item "Second Window" from drop-down list
Select lstSecondWindow = new Select(driver.findElement(By.id("list-second-window")));
lstSecondWindow.selectByVisibleText("Second Window");
//Click on link that opens third window
driver.findElement(By.linkText("Click Me To Open Third Window")).click();
//Storing the collection of all opened windows (in our case it would be 3)
Set<String> setNewWindowHandles = driver.getWindowHandles();
//Iterating over all windows handles
for(String strWindowHandle: setNewWindowHandles){
	//If the window handle is not same as the First and Second window handles, it is the new window
	if(	(!strWindowHandle.equals(strFirstWindowHandle))	&&	(strWindowHandle.equals(strSecondWindowHandle)	){
		//Switch to the new window
		driver.switchTo().window(strWindowHandle);
		//Print window title
		System.out.println(driver.getTitle());
		break;
	}
}


//Select the item "Third Window" from drop-down list
Select lstSecondWindow = new Select(driver.findElement(By.id("list-second-window")));
lstSecondWindow.selectByVisibleText("Third Window");


//Switch back to first window
driver.switchTo().window(strFirstWindowHandle);

driver.quit();
from selenium import webdriver
from selenium.webdriver.support.ui import Select

chrome_driver_path = "C:/teachmeselenium/chromedriver.exe"
driver = webdriver.Chrome(chrome_driver_path)
driver.get("https://cosmocode.io/automation-practice")

#Get current window handle
parent_window_handle = driver.current_window_handle
#Click on the link
driver.find_element_by_link_text("Click Me to open New Window").click()
driver.switch_to.window("Beginner | Automation Practice – 2nd Window – Teach me Selenium")
select = Select(driver.find_element_by_id("list-second-window"))
select.select_by_visible_text("Second Window")
#Get window handles
old_window_handles = driver.window_handles()
#Perform action that will open new window
driver.find_element_by_link_text("Click Me To Open Third Window").click()
#Get new window handles
new_window_handles = driver.window_handles()
#Getting one Window handle each time the loop runs
for window_handle in new_window_handles:
    #If this window handle is not found in the collection of Old Window handles,
    #it must be the new one
    if window_handle not in old_window_handles:
        #Switch to the new window
        driver.switch_to.window(window_handle)
        print(driver.title)
        #Exit from loop
        break

#Switch back to parent window
driver.switch_to.window(parent_window_handle)
print(driver.title)

driver.quit()

In the Next Tutorial, we’ll learn one of the powerful features of Selenium WebDriver – How to do cross-browser execution?

11 thoughts on “Handling Alert dialog, Popup windows and Frames | Handling Popup windows”

  1. Getting below error

    Exception in thread "main" org.openqa.selenium.NoSuchWindowException: Unable to locate window "Automation Practice Second Window ~ Teach Me Selenium"
    Command duration or timeout: 4.18 seconds

    here is the code

    WebDriver driver = new FirefoxDriver();
    driver.get("https://cosmocode.io/p/automation-practice.html&quot;);

    driver.findElement(By.linkText("Click Me to open New Window")).click();

    driver.switchTo().window("Automation Practice Second Window ~ Teach Me Selenium");
    Select lstSecondWindow = new Select(driver.findElement(By.id("list-second-window")));
    lstSecondWindow.selectByVisibleText("Second Window");

    No selection is happening,, only two different windows are getting opened in firefox

    please check
    Regards
    Gaurav Khurana

    http://www.Udzial.com
    Udzial Means share

    Reply
  2. Hi Gaurav.. my bad πŸ™ … I missed to comment this line – driver.switchTo().window("Automation Practice Second Window ~ Teach Me Selenium"); I believe you read the section Step #4 Updated. I have updated the code. Please take the latest code from there.

    Reply
  3. I've made compilation of all your tasks πŸ˜‰

    import org.openqa.selenium.Alert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.Select;
    import org.openqa.selenium.support.ui.WebDriverWait;

    import java.util.Set;
    import java.util.concurrent.TimeUnit;

    public class Practicing {

    public static void main(String[] args) {
    WebDriver driver = new FirefoxDriver();

    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get("https://cosmocode.io/p/automation-practice.html&quot;);

    WebDriverWait wait = new WebDriverWait(driver,5);

    if(driver.findElements(By.id("firstname")).size() > 0)
    driver.findElement(By.id("firstname")).sendKeys("TestFirstName");

    driver.findElement(By.className("lastname")).sendKeys("TestLastName");

    driver.findElement(By.xpath("//input[@value='Male']")).click();

    driver.findElement(By.cssSelector("input[value=java]")).click();

    WebElement lstAge = driver.findElement(By.name("age"));
    Select selectAge = new Select(lstAge);
    selectAge.selectByVisibleText("30 to 39");

    driver.findElement(By.name("submit")).click();

    driver.findElement(By.linkText("Click Me to get Alert")).click();
    Alert alert = driver.switchTo().alert();
    String AlertText = alert.getText();
    System.out.println(AlertText);
    alert.dismiss();

    String ParentWindowHandle = driver.getWindowHandle();
    driver.findElement(By.linkText("Click Me to open New Window")).click();
    Set setWindowHandles = driver.getWindowHandles();
    for(String strWindowHandle: setWindowHandles){
    if (!strWindowHandle.equals(ParentWindowHandle)){
    driver.switchTo().window(strWindowHandle);
    System.out.println(driver.getTitle());
    break;
    }
    }

    Select SecondWindow = new Select(driver.findElement(By.id("list-second-window")));
    SecondWindow.selectByVisibleText("Second Window");
    Set setOldWindowHandles = driver.getWindowHandles();
    driver.findElement(By.linkText("Click Me To Open Third Window")).click();
    Set setNewWindowHandles = driver.getWindowHandles();
    for(String strWindowHandle: setNewWindowHandles) {
    if (!setOldWindowHandles.contains(strWindowHandle)){
    driver.switchTo().window(strWindowHandle);
    System.out.println(driver.getTitle());
    break;
    }
    }
    driver.switchTo().window(ParentWindowHandle);

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("GoToHomepage")));
    driver.findElement(By.partialLinkText("GoToHomepage")).click();

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("search")));
    driver.quit();

    }
    }

    Reply
  4. Great job Alexey ) … It would be great if you can also contribute in resolving other readers queries as well… We all can work together and help each other on this platform.

    Reply
  5. I am using chrome

    Using the following opened the link in new tab and not window

    driver.findElement(By.linkText("Click Me to open New Window")).click();

    So I used this

    String selectAll = Keys.chord(Keys.SHIFT,Keys.RETURN);
    driver.findElement(By.linkText("Click Me to open New Window")).sendKeys(selectAll);

    It opened a new window
    Then I did this but it failed to find the window

    driver.switchTo().window("Automation Practice Second Window ~ Teach Me Selenium");

    Any ideas?
    Nice blog BTW. Very Helpfull.

    Reply

Leave a Reply