How to handle the new window in Selenium WebDriver using Java?

后端 未结 6 2131
北海茫月
北海茫月 2020-11-27 18:59

This is my code:

driver.findElement(By.id(\"ImageButton5\")).click();
//Thread.sleep(3000);
String winHandleBefore = driver.getWindowHandle();
driver.switchT         


        
6条回答
  •  北海茫月
    2020-11-27 19:19

    I have an utility method to switch to the required window as shown below

    public class Utility 
    {
        public static WebDriver getHandleToWindow(String title){
    
            //parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
            WebDriver popup = null;
            Set windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
            System.err.println("No of windows :  " + windowIterator.size());
            for (String s : windowIterator) {
              String windowHandle = s; 
              popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
              System.out.println("Window Title : " + popup.getTitle());
              System.out.println("Window Url : " + popup.getCurrentUrl());
              if (popup.getTitle().equals(title) ){
                  System.out.println("Selected Window Title : " + popup.getTitle());
                  return popup;
              }
    
            }
                    System.out.println("Window Title :" + popup.getTitle());
                    System.out.println();
                return popup;
            }
    }
    

    It will take you to desired window once title of the window is passed as parameter. In your case you can do.

    Webdriver childDriver = Utility.getHandleToWindow("titleOfChildWindow");
    

    and then again switch to parent window using the same method

    Webdriver parentDriver = Utility.getHandleToWindow("titleOfParentWindow");

    This method works effectively when dealing with multiple windows.

提交回复
热议问题