1. First, acquire new window handle by using the switchTo() method.
2. Then bring that window into focus using a JavaScriptExecutor:
((JavascriptExecutor) myTestDriver).executeScript("window.focus();");
Using switchTo() without a javascript executor to get focus , is not
very reliable in my opinion.
3. Next, do what you need to do in that window.
4. Use driver.close() to close that window.
5. Verify you are back at the parent window with focus.
Go Back
${Current_window} List Windows
Click Element ${LINKDIN}
${New_Windows_list} List Windows
Should Not Be Equal ${Current_window} ${New_Windows_list}
@Test
public void targetBlankLinkTest() {
// load the website and make sure only one window is opened
driver.get(file("TargetBlankLinkTest.html"));
assertEquals(1, driver.getWindowHandles().size());
// click the link and assert that a new window has been opened
driver.findElement(By.linkText("Follow us on Twitter!")).click();
Set<String> windowHandles = driver.getWindowHandles();
assertEquals(2, windowHandles.size());
// switch to the new window and do whatever you like
// (Java doesn't have Switch Window functionality that can select by URL.
// I could write it, but have been using this trick instead)
for (String handle : windowHandles) {
if (handle != driver.getWindowHandle()) {
driver.switchTo().window(handle);
}
}
assertThat(driver.getCurrentUrl(), containsString("twitter.com"));
}
0
你可以使用下面的代码来设置焦点在新窗口:
单击元素$ 选择窗口新建
现在,您可以在新标签上执行操作 . 如果你想切换回主标签然后使用
选择窗口Main
0
使用Robot Selenium2Library关键字:
@{windows} = List Windows
${numWindows} = Get Length ${windows}
${indexLast} = Evaluate ${numWindows}-1
Should Be True ${numWindows} > 1
Select Window @{windows}[${indexLast}]
Location Should Contain /my/url/whatever
Title Should Be myTitle
Page Should Contain ...
5 回答
我建议:
如果要验证是否已打开新选项卡,则可以在单击打开新选项卡的链接/元素之前和之后比较窗口句柄 . 只需遵循此代码可能对您有所帮助 .
这里$ 是在新标签页中打开的元素 . 所以在点击之前将窗口句柄保存在变量中,再次单击该元素后,将窗口句柄保存在变量中 . 现在,如果打开一个新的选项卡,那么变量值将不同,如果没有打开新选项卡,则两个变量值都相同 . 这样就可以验证新的开启 .
Selenium不支持标签(截至2013年6月,Selenium 2.33.0)并且总是打开新窗口 . 如果你的测试打开一个新标签,祝你好运 .
也就是说,如果它正确打开一个新窗口,请使用Select Window .
我在Java中使用的是WebDriver(2.33.0)代码,希望它会有所帮助 . 你所描述的问题是我的机器人知识开始脱落的地方 .
你可以使用下面的代码来设置焦点在新窗口:
单击元素$ 选择窗口新建
现在,您可以在新标签上执行操作 . 如果你想切换回主标签然后使用
选择窗口Main
使用Robot Selenium2Library关键字:
你明白了 .