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

后端 未结 6 2142
北海茫月
北海茫月 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:12

    It seems like you are not actually switching to any new window. You are supposed get the window handle of your original window, save that, then get the window handle of the new window and switch to that. Once you are done with the new window you need to close it, then switch back to the original window handle. See my sample below:

    i.e.

    String parentHandle = driver.getWindowHandle(); // get the current window handle
    driver.findElement(By.xpath("//*[@id='someXpath']")).click(); // click some link that opens a new window
    
    for (String winHandle : driver.getWindowHandles()) {
        driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
    }
    
    //code to do something on new window
    
    driver.close(); // close newly opened window when done with it
    driver.switchTo().window(parentHandle); // switch back to the original window
    

提交回复
热议问题