In
automation there are many situations where we need to handle
multiple windows.
Generally
multiple windows will open when we perform any click action on a link
or any button/ web-element etc based on the application behavior.
Selenium webdriver get all the window sessions which are opened through automation(driver instance).
Selenium webdriver get all the window sessions which are opened through automation(driver instance).
Internally
webdriver assigns an uniques alphanumeric id to each and every window
when WebDriver object is instantiated.
By
using this unique alphanumeric id, Selenium can differentiate when it
is switching controls from one window to the other.
How
to handle and get the current window :
String parentWindow=driver.getWindowHandle();//Return uniqueId value
How
to get all the open windows:
Setwindows=driver.getWindowHandles();//Return a set of unique alphanumeric values of all the windows. for(String windowName : windows) { driver.switchTo().window(windowName);//Switch to child window name //Perform your desired selenium actions driver.close();//closing the child Window }
How
to switch to Parent Window:
driver.switchTo().window(parentWindow);//Switch back to the parent window
How
to switch to window based on window title:
String windowTitle=”Google”; Setwindows=driver.getWindowHandles();//Return a set of unique alphanumeric values of all the windows. for(String windowName : windows) { driver.switchTo().window(windowName);//Switch to child window name if(driver.getTitle().equalsIgnoreCase(windowTitle) { //Perform your desired actions } //Close the child windowName driver.close(); } driver.switchTo().window(parentWindow);//Switch back to the parent window
Complete
Code:
String windowTitle="Google"; String parentWindow=driver.getWindowHandle();//Return a unique id value Setwindows=driver.getWindowHandles();//Return a set of unique alphanumeric values of all the windows. for(String windowName : windows) { driver.switchTo().window(windowName);//Switch to child window name if(driver.getTitle().equalsIgnoreCase(windowTitle)) { //Perform your desired actions } //Close the child windowName driver.close(); } driver.switchTo().window(parentWindow);//SwitchBack to the Parent-window