Saturday, 11 August 2018

Handling multiple windows in selenium

Handling Window Pop Up In Selenium: 

There may be a situation while doing automation where we need to handle multiple window popup or where we need to go to appropriate window among multiple windows at run time. Selenium code /automation get focused on default/parent window.
E.g If you navigate or go to Naukri.com url then you will get multiple window pop up only when if you haven't disable pop up option.

Here, How do we know that it is a window popup or java script pop up or Jquery/Normal pop up.

Window Pop up:

           Window pop up has minimize, maximize and close button like any normal browser has.
            driver.switchTo().window("windowName);
            driver.switchTo().window();
         
           Here driver referes to webDriver object -

           WebDriver driver = new ChromeDriver();

Java Script Pop Up: 

           Java script pop up doesn't have minimize or maximize button/option also focus is only on java script pop up page. you can't ignore the java script popup but window pop up you can ignore it and perform operation on any other windows.

Ways to Handle Window Pop Up in Selenium:
    
           Selenium webdriver assign unique id (alpha numeric ) to every window to identify uniquely. The alpha numeric id (unique id) is called "Window Handle" in selenium.

How to get Window Handle:

          String handle = driver.getWindowHandle();

If there are multiple window gets opened when you click on any link,button etc... then to get "window Handle" of each window -

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

"getWindowHandles()" : method return window handle (unique id for each opened window) so that the return type is set. Because set will not contain duplicate elements so here getWindowHandles return unique id/window handles for each winodw and stored in Set.

How to switch to correct / appropriate window:

          Basically there are two ways to switch to appropriate window.

  1. By using windowName
         driver.switchTo().window( "windowName" );
        or
     
     2.  To get current/parent/default window handle:

        String handle = driver.getWindowHandle();
        driver.switchTo().window( handle  );

        or

        Set < String > windowHandles = driver.getWindowHandles();
        for(String handle : windowHandles )
         {
             driver.swicthTo().window( handle ); 
        }


Example:





No comments:

Post a Comment