There are many such cases now a days, where any application (web site) displays multiple windows pop up, when you open a website for any purpose. Those are may be some kind of advertisements or may be, some information are showing on popup windows. We can handle those thing via using Windows Handlers in selenium webdriver API.
Step 1: Opening any website, we need to get the main window handle by using below syntex driver.getWindowHandle();
Window handle shall be in a form of lengthy alpha numeric data
Step 2: If we need to get all the window handles by using driver.getWindowHandles(); command
Step 3: We can compare all the window handles with the main Window handles and perform the operation the window whatever we need.
The below example explain how to handle multiple windows and close all the child windows which are not need. We need to compare the main window handle to all the other window handles and close them.
package
com.suit;
import
java.util.Set;
import
org.openqa.selenium.WebDriver;
import
org.openqa.selenium.firefox.FirefoxDriver;
import
org.testng.Assert;
import
org.testng.annotations.Test;
public
class WindowhandlearExamples {
WebDriver driver;
@Test
public void CloseAllWindowsExceptMainWindow_test()
{
driver = new FirefoxDriver();
// It will open the Naukri.com
website with multiple windows
driver.get("http://www.naukri.com/");
// To find the main window handle
String getwindowTitle=
getCurrentWindowTitle();
String getmainWindow =
getMainWindowHandle(driver);
Assert.assertTrue(closeAllOtherWindows(mainWindow));
Assert.assertTrue(grtwindowTitle.contains("Jobs
- Recruitment"), "Main window title is not matching");
}
public String getMainWindowHandle(WebDriver
driver) {
return driver.getWindowHandle();
}
public String getCurrentWindowTitle() {
String windowTitle =
driver.getTitle();
return windowTitle;
}
//To close all the other windows except
the main window here we go.
public static boolean closeAllOtherWindows(String
openWindowHandle) {
Set<String>
allWindowHandles = driver.getWindowHandles();
for (String currentWindowHandle :
allWindowHandles) {
if
(!currentWindowHandle.equals(openWindowHandle)) {
driver.switchTo().window(currentWindowHandle);
driver.close();
}
}
driver.switchTo().window(openWindowHandle);
if
(driver.getWindowHandles().size() == 1)
return true;
else
return false;
}
}
No comments:
Post a Comment