Selenium Webdriver Switch Window Commands
Some web applications have many frames or
multiple windows. Selenium WebDriver assigns an alphanumeric id to each window
as soon as the WebDriver object is instantiated. This unique alphanumeric id is
called window handle. Selenium uses
this unique id to switch control among several
windows. In simple terms, each unique window has a unique ID, so that Selenium
can differentiate when it is switching controls from one window to the other.
GetWindowHandle Command
Purpose: To
get the window
handle of
the current window.
String handle=
driver.getWindowHandle();//Return a string of alphanumeric window handle
GetWindowHandles Command
Purpose: To
get the window
handle of all the current windows.
Set<String> handle= driver.getWindowHandles();//Return
a set of window handle
SwitchTo Window Command
Purpose:
WebDriver supports moving between named windows using the
“switchTo” method.
driver.switchTo().window("windowName");
Or
Alternatively, you can pass a
“window handle”
to the “switchTo().window()” method. Knowing this, it’s possible to iterate
over every open window like so:
for (String handle : driver.getWindowHandles())
{
driver.switchTo().window(handle);
}
Switching between windows with Iterators:
driver.findElement(By.id(“id of the link which opens new
window”)).click();
//wait till two
windows are not opened
waitForNumberofWindowsToEqual(2);//this method
is for wait
Set handles =
driver.getWindowHandles();
firstWinHandle =
driver.getWindowHandle(); handles.remove(firstWinHandle);
String
winHandle=handles.iterator().next();
if
(winHandle!=firstWinHandle){
//To retrieve the
handle of second window, extracting the handle which does not match to first
window handle
secondWinHandle=winHandle; //Storing handle of
second window handle
//Switch control to new window
driver.switchTo().window(secondWinHandle);
Comments
Post a Comment