如何使用Java关闭Selenium WebDriver中的子浏览器窗口

切换到新窗口并完成任务后,我想关闭该新窗口并切换到旧窗口,

所以在这里我写得像代码:

// Perform the click operation that opens new window

String winHandleBefore = driver.getWindowHandle();

    // Switch to new window opened

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

    // Perform the actions on new window


    driver.findElement(By.id("edit-name")).clear();
    WebElement userName = driver.findElement(By.id("edit-name"));
    userName.clear();
              try
    {
        driver.quit();
    }

    catch(Exception e)
    {
        e.printStackTrace();
        System.out.println("not close");
                }

driver.switchTo().window(winHandleBefore);// Again I want to start code this old window

上面我写的代码或.但是我遇到了错误。任何人都可以帮我...?driver.quit()driver.close()

org.openqa.selenium.remote.SessionNotFoundException:FirefoxDriver 在被调用 quit() 后无法使用。


答案 1

要关闭单个浏览器窗口:

driver.close();

要关闭所有(父级+子级)浏览器窗口并结束整个会话,请执行以下操作:

driver.quit();

答案 2

用于将控件切换到弹出窗口的逻辑是错误的

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

上述逻辑如何将控件切换到新窗口?


使用以下逻辑将控件切换到新窗口

// 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();

推荐