0

Webdriver launches multiple windows after performing click action. I have tried driver.close() but it close the webdriver and test fails.

            WebDriver driver = new FirefoxDriver ();
    driver.get("http://www.xyz.com/");
    JavascriptExecutor js = (JavascriptExecutor) driver;

    WebElement page = driver.findElement(By.className("coupon-rows"));

          List <WebElement>  coupontrigger = page.findElements(By.className("code"));
              System.out.println("number of couponsTriggers on carousel = "+ "coupontrigger.size());

   for (int j=0; j<=coupontrigger.size(); j++) {


      js.executeScript("$('.ccode.coupon-trigger').eq("+j+").click()");

      System.out.println(driver.getTitle());

      driver.switchTo().defaultContent();

      driver.get("http://www.xyz.com/");
      page = driver.findElement(By.className("coupon-rows"));
      coupontrigger = page.findElements(By.className("code"));

     }
}
OPY
  • 15
  • 3

2 Answers2

0

If I understood your requirement you want to close the other popups rather than the main window. In that case you can do below. Though I am not 100% sure of your requirement.

String mwh=driver.getWindowHandle(); // Get current window handle
Set<String> s=driver.getWindowHandles();
Iterator<String> ite=s.iterator();
String popupHandle = "";
while(ite.hasNext())
{
    popupHandle = ite.next().toString();
    if(!popupHandle.contains(mwh)) // If not the current window then shift focus and close them
    {
         driver.switchTo().window(popupHandle);
         driver.close();
    }
 }
 driver.switchTo().window(mwh); // finally move control to main window.
A Paul
  • 8,113
  • 3
  • 31
  • 61
0

You can introduce a helper method which will do that task for you. You just need to find out what your current view is (WebDriver#getWindowHandle will give the one you have focus on) and then just close the rest of the windows.

private String closeAllpreviouslyOpenedWindows() {
    String firstWindow = webDriver.getWindowHandle();
    Set<String> windows = webDriver.getWindowHandles();
    windows.remove(firstWindow);
    for (String i : windows) {
        webDriver.switchTo().window(i);
        webDriver.close();
    }
    webDriver.switchTo().window(firstWindow);
    return firstWindow;
}
Petr Mensik
  • 26,874
  • 17
  • 90
  • 115
  • Thanks Petr your code works great. it really helped. Thank you so much for your time and effort really appreciate it! – OPY Jan 04 '14 at 00:39
  • i need 15 reputations to up-vote your answer currently I have only 3. but in future i will do it! Thanks again. – OPY Jan 05 '14 at 20:43