How to close child browser window in Selenium WebDriver using Java

后端 未结 7 1646
傲寒
傲寒 2020-12-14 16:07

After I switch to a new window and complete the task, I want to close that new window and switch to the old window,

so here i written like code:

// P         


        
7条回答
  •  星月不相逢
    2020-12-14 16:56

    The logic you've used for switching the control to popup is wrong

     for (String winHandle : driver.getWindowHandles()) {
            driver.switchTo().window(winHandle);
        }
    

    How the above logic will swtich the control to new window ?


    Use below logic to switch the control to new window

    // get all the window handles before the popup window appears
     Set beforePopup = driver.getWindowHandles();
    
    // click the link which creates the popup window
    driver.findElement(by).click();
    
    // get all the window handles after the popup window appears
    Set afterPopup = driver.getWindowHandles();
    
    // remove all the handles from before the popup window appears
    afterPopup.removeAll(beforePopup);
    
    // there should be only one window handle left
    if(afterPopup.size() == 1) {
              driver.switchTo().window((String)afterPopup.toArray()[0]);
     }
    

    // Perform the actions on new window

      **`//Close the new window`** 
        driver.close();
    

    //perform remain operations in main window

       //close entire webDriver session
        driver.quit();
    

提交回复
热议问题