CosmoCode (Formerly TeachMeSelenium)

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
driver.findElement(By.linkText("Click Me to open New Window")).click();
driver.find_element_by_link_text("Click Me to open New Window").click()

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
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")
driver.findElement(By.linkText("Click Me To Open Third Window")).click();
driver.find_element_by_link_text("Click Me To Open Third Window").click()
Set<String> setNewWindowHandles = driver.getWindowHandles();
new_window_handles = driver.window_handles()
//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?

Exit mobile version