No Such window exception: selenium web driver

No Such window exception, Selenium web driver throws an exception when it is trying access the window and it is not available to reach and launch.

In order to handle this exception, we need to add the line of code in the try and catch blocks with no such window exception.

       driver.get(AppUrl); // Will launch the application URL

        String parentWindowHandle = driver.getWindowHandle();

        System.out.println(” handles the parent: ” + parentWindowHandle);

        WebElement newwindowlink = driver.findElement(By.xpath(“xpathNewwindow”));

        newwindowlink.click();

        Set<String> windowsHandles = driver.getWindowHandles();

        for(String handle: windowsHandles){

            if(!handle.equals(parentWindowHandle)){

            driver.switchTo().window(handle);

            Thread.sleep(1000);

            System.out.println(“Title of the new window: ” +

driver.getTitle());

            System.out.println(“Closing the new window”);

            driver.close();

From the above code, line marked with red color is switch to window handle, driver is trying to reach and access the new window, as the new window is not loading at this point, script will fail to run and throw exception as no such window exception.

In order to handle this exception, we need to add this command in try and catch block with no such window exception.

        Set<String> windowsHandles = driver.getWindowHandles();

try{

        for(String handle: windowsHandles){

            if(!handle.equals(parentWindowHandle)){

            driver.switchTo().window(handle)

            Thread.sleep(1000);

            System.out.println(“Title of the new window: ” +

driver.getTitle());

            System.out.println(“Closing the new window…”);

            driver.close();

                }catch(NoSuchWindowException e)

{

system.out.println(“the exception is : “+e);

}

The above line of code will give:

  1. the try and catch block will catch the exception
  2. The exception handle is given in the console.
  3. Cross check again and confirm that the application has error at the link to open window in your application.

Leave a Comment

Your email address will not be published. Required fields are marked *