小编典典
您需要做两件事:
在IE浏览器中更改安全设置:
打开IE浏览器,单击“ Internet选项” =>“安全性” =>选中“启用保护模式”,用于“
Internet”,“本地Intranet”,“受信任的站点”和“受限制的站点”。
这使IE驱动程序能够控制新窗口的句柄,以便在调用
driver.getWindowHandles();或driver.getWindowHandles().size();
时将获得所有句柄,包括原始窗口和新窗口。为了更加准确,您只需要将所有4个域的安全性设置都设置为相同即可,这意味着您可以取消选中所有4个域的“启用保护模式”,但是显然不建议这样做。
调用之后driver.switchTo().window(windowName);,需要添加((JavascriptExecutor) driver).executeScript("window.focus();");IE驱动程序才能在窗口上执行任何操作。
这是因为IE驱动程序需要它正在处理的窗口在前台,因此此行可帮助驱动程序获取窗口的焦点,以便它可以在所需的窗口上执行任何操作。
以下是一个完整的示例:
String baseWin = driver.getWindowHandle();
//Some methods to open new window, e.g.
driver.findElementBy("home-button").click();
//loop through all open windows to find out the new window
for(String winHandle : driver.getWindowHandles()){
if(!winHandle.equals(baseWin)){
driver.switchTo().window(winHandle);
//your actions with the new window, e.g.
String newURL = driver.getCurrentUrl();
}
}
//switch back to the main window after your actions with the new window
driver.close();
driver.switchTo().window(baseWin);
//let the driver focus on the base window again to continue your testing
((JavascriptExecutor) driver).executeScript("window.focus();");
2020-11-30