Multiple Windows in Selenium Webdriver

There will be times when you will required to perform some testing, where the testing operations open a new browser/tab, testcase may required you to perform some tasks on the newly opened browser window/tab and return back to original window to perform the remaining tasks.

Even if the window/tab is currently on focus but still it is not an active window, so to perform some tasks you need to switch to new browser window/tab in selenium webdriver.

Commands will have effect on base window unless we switch our control to new window/tab.

Previously tab and Windows are two different items, as tabs does not had any GU iD. Now developers made tab and windows have GUIDs, so tabs and windows are treated as same in selenium webdriver

Situations when we are likely to deal with multiple windows:

Filling forms may require to select the date from a separately opened window
Clicking on some link/button can open another window
Handling Advertisement windows

Multiple Windows


multiple-windows-handling-selenium-webdriver Above image depicts multiple browser windows

1. Our Application is opened on Parent/Base window, total number of windows is one

2. When clicking on a link/button our application opens two new windows along with base window, now the total number of windows present is Three (base + child-1 + child-2)

3. Now move to Child-1 window and perform click on a button/link which open another one more window along with child-window, now the total number of windows is 4 (base + child-1 + child-2 + grand child-1)

4. We can perform operation on grand child -1 window and we can close all windows or specif windows.

If we perform above operation manually, we may not find difficulty, but handling above scenario is tricky in selenium webdriver

Get Window Handles in Selenium webdriver

Selenium webdriver provides few methods to handle the multiple windows, let's see what are the methods and their uses.

GU ID:
GU ID abbreviation of Globally Unique Identifier, Every OS generates GU ID for application to identify them uniquely. We will be using this GU ID to handle the multiple browsers, GU ID is numeric string value.


										8589934593
										


current_window_handle :
current_window_handle method in selenium webdriver returns the current(active) browser's GU ID. It return GU ID as string value.


										driver.current_window_handle;
										


current_window_handle :
getWindowHandles method in selenium webdriver returns GU ID of all the browsers present at the moment, which are openend by current driver. This method returns GU IDs as Set of String.


										driver.window_handles;
										


switch_to_window() : switchTo() method in selenium webdriver helps user to switch between windows, frames, elements, alerts. switch_to_window(GU ID) method switches the control from the current browser window to target browser window which has the speccified "GU ID".


										driver.switch_to_window(guid);
										

Handle simple Two Browser Windows / Tabs

Click the button to Open a new window ( google.com)

Please use firefox as browser to open the link in new window, if you use chrome the link may be opened in new tab rather than new window.

two-windows-example-selenium-webdriver Steps to Handle Two Windows :
1. Open chrome browser and Navigate to https://chercher.tech/python/windows-selenium-python


										# open chrome browser			
										driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
										# set implicit time to 30 seconds
										driver.implicitlyWait(30);
										# navigate to the url
										driver.get("https://chercher.tech/python/windows-selenium-python");
										


2. Get the GU ID of the current (parent) window using current_window_handle method present in the selenium webdriver and store the value in a String


										# get the Session id of the Parent
										parentGUID = driver.current_window_handle;
										


3. Click on the Open New Window button, application open new window with google page. Make the selenium webdriver to sleep for 5 seconds, otherwise it may not fnd the newly pened tab.


										# click the button to open new window
										driver.find_element_by_id("two-window").click();
										time.sleep(5000);
										


4. Get the GU IDs of the two windows (parent + google), using window_handles method present in the Selenium webdriver. Store the GU IDs in a Set Collection, this Set will have GU IDs of both parent and Child Browsers


										# get the All the session id of the browsers
										allGUID = driver.window_handles;
										


5. iterate the Set of GUID values, and if the value is parent value skip it if not switch to the new window


										# iterate the values in the set
										for guid in all allGUID:
											# one enter into if blobk if the GUID is not equal to parent window's GUID
											if(guid != parentGUID):
												# todo 
											
										
										


6. Switch to window using switch_to_window() method present in selenium webdriver, pass the GU ID of the child browser to this method.


										# switch to the guid
										driver.switch_to_window(guid);
												
										


7. Find the search bar in Google.com and search for "success"


										# search on the google page
										driver.find_element_by_name("q").send_keys("success");
										


Close the Google tab/Window and return to parent tab/browser window


										# close the browser
										driver.close();
										# switch back to the parent window
										driver.switch_to_window(parentGUID);
										

Complete code for switching window may look like below


										class TwoWindows(unittest.TestCase) :
											def test_browser_Window :
												# open chrome browser			
												driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
												# set implicit time to 30 seconds
												driver.implicitlyWait(30);
												# navigate to the url
												driver.get("https://chercher.tech/python/windows-selenium-python");
												# get the Session id of the Parent
												parentGUID = driver.current_window_handle;
												# click the button to open new window
												driver.find_element_by_id("two-window").click();
												time.sleep(5000);
												# get the All the session id of the browsers
												allGUID = driver.window_handles;
												# pint the title of th epage
												print("Page title before Switching : "+ driver.getTitle());
												print("Total Windows : "+allGUID.size());
												# iterate the values in the set
												for guid in all allGUID:
													# one enter into if blobk if the GUID is not equal to parent window's GUID
													if(guid != parentGUID):
														# switch to the guid
														driver.switch_to_window(guid);
														# break the loop
														break;
													
												
												# search on the google page
												driver.find_element_by_name("q").send_keys("success");
												# print the title after switching
												print("Page title after Switching to goolge : "+ driver.getTitle());
												time.sleep(5000);
												# close the browser
												driver.close();
												# switch back to the parent window
												driver.switch_to_window(parentGUID);
												# print the title
												print("Page title after switching back to Parent: "+ driver.getTitle());
											
										
										
										
										


output-two-window-selenium-webdriver

More than Two Window handling

We have handled the two windows in above tutorial by comparing GUID but when we have more than two window we cannot use the same approach. To access the exact page we may need title of the page, based on the title of the page we can differentiate the browser windows in selenium.

Tip : We can use title, url, element reference while switching into new window to ensure that we are switching to the required window. I prefer Tile, url than element



Scenario : Click on the Open 3 New Windows button, it will open three more windows (bing, google, yahoo), now switch to bing and search for "gates". four-windows-example-selenium-webdriver Steps to Handle More than Two Windows :
1. Open firefox browser and Navigate to https://chercher.tech/python/windows-selenium-python

2. Get the GU ID of the current (parent) window using current_window_handle method present in the selenium webdriver and store the value in a String

3. Click on the Open 3 New Window button, application open new window with google page. Make the selenium webdriver to sleep for 5 seconds, otherwise it may not fnd the newly pened tab.

4. Get the GU IDs of the two windows (parent + google + bing + yahoo), using window_handles method present in the Selenium webdriver. Store the GU IDs in a Set Collection, this Set will have GU IDs of both parent and Child Browsers

5. Now iterate through the Set,switch to first GUID in Set and check the page title contains the keyword "bing".

Complete program for switching multiple windows in selenium webdriver


										class MoreThanTwoWindows(unittest.TestCase) :
											def test_browser_Window :
												
													# open chrome browser			
													driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
													# set implicit time to 30 seconds
													driver.implicitlyWait(30);
													# navigate to the url
													driver.get("https://chercher.tech/python/windows-selenium-python");
													# get the Session id of the Parent
													parentGUID = driver.current_window_handle;
													# click the button to open new window
													driver.find_element_by_id("three-window").click();
													time.sleep(5000);
													# get the All the session id of the browsers
													allGUID = driver.window_handles;
													# print number of windows
													print("Total Windows : "+allGUID.size());
													//iterate through windows
													for guid in all allGUID:
														driver.switch_to_window(guid);
														# check the title of the page to match with "bing"
														if("bing" in driver.title.lower()):
															driver.findElement(By.className("b_searchbox").send_keys("gates");
															time.sleep(3000);
															break;
														
													
													# close all the windows
													driver.quit();
											
										
										

How do developer make the link to open in New Window

Developer can make the link to open in new window using target keyword present in anchor tag <a>, when developer set this value to "_blank", the link will be opened in new windows when user clicks the link.


											# button is nested inside a link
											<a id='two-window' href='https://google.com' target='_blank'><input type='button' value="Open New Window"></a>
											# plain link
											<a id='two-window' href='https://google.com' target='_blank'>Click me</a>
										


If developer avoids to use target='_blank', browser opens such links in same window. It is recommended not to open the link in new window


										<a id='two-window' href='https://google.com'>Click me</a>
										

Force to open in new Window rather than Tab

There will be situatons where we have to open a link in new Window, but later browser donot support opening a url in new window as it is not recommended ( phishing is easy with with new windows ).

During such scenarios we can use action class to open the link in new window, by pressing Shift key and to click the link, it opens the link in new window in selenium webdriver.

Steps to open link in a new Window :
1. Open firefox browser and Navigate to https://chercher.tech/python/windows-selenium-python


										# open chrome browser			
										driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
										# set implicit time to 30 seconds
										driver.implicitlyWait(30);
										


2. Find the above link using id force-new-window and store it in a variable of type


										# store the element
										ele = driver.find_element_by_id("force-new-window");
										


3. Create a object for Actions class


										# create object for Actions class
										act = ActionChains(driver);
										


4. Call key_down method from the Actions class object, and pass Keys.SHIFT as parameter

5. Call Click method from the Actions class object, pass stored web element as parameter to this method

6. Use build() method from Actions class object to bind the key_down and click methods, call the perform method to perform the operations.


										# press the shift key
										act.key_down(Keys.SHIFT).click(ele).build().perform();
										


Complete program for opening a link in new window in selenium webdriver.


										class OpenNewWindow(unittest.TestCase) :
											def test_browser_Window :
												# open chrome browser			
												driver = webdriver.Chrome(executable_path=r'D:\PATH\chromedriver.exe')
												# set implicit time to 30 seconds
												driver.implicitlyWait(30);
												# navigate to the url
												driver.get("https://chercher.tech/python/windows-selenium-python");
												# get the Session id of the Parent
												parentGUID = driver.current_window_handle;
												# store the element
												ele = driver.find_element_by_id("force-new-window");
												# create object for Actions class
												act = ActionChains(driver);
												# press the shift key
												act.key_down(Keys.SHIFT).click(ele).build().perform();
											
										
										

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
You can also share knowledge by Adding a topic here


Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Protractor Online Training : We have closed registration for training

Please do email to chercher.tech@gmail.com for any queries

If you already registered then please do check your email for the Webex link for the training starting from 15th Nov 2018
 
Join My Facebook Group
Join Group