IE9上的Selenium JavascriptExecutor导致'元素没有滚动到视窗中'错误
Selenium JavascriptExecutor on IE9 results in 'element was not scrolled into the viewport' error
我正在尝试使用JavascriptExecutor从selenium webdriver打开IE9中的新选项卡:
public void openTab() {
String url = webDriver.getCurrentUrl();
String script = "var a=document.createElement('a');a.target='_blank';a.href='" + url + "';a.innerHTML='open';document.body.appendChild(a);return a";
Object element = getJSExecutor().executeScript(script);
if (element instanceof WebElement) {
WebElement anchor = (WebElement) element;
anchor.click();
} else {
throw new RuntimeException("Unable to open tab: " + url);
}
}
这在Chrome中工作正常,但在IE9中运行时,我得到以下错误:
ElementNotVisibleException:驱动程序试图点击元素的点没有滚动到视图中。
我使用的是2.31版本的selenium和IEDriverServer。
我在并行虚拟机的IE9中一直遇到这个问题。这是使整个程序工作的两行代码…
Actions builder = new Actions(webDriver);
builder.moveToElement(element).click(element).perform();
将元素滚动到视图中,然后单击它
成功解决了视口问题&让IEDriverServer与两个窗口进行适当的交互,经过一点哄骗,所以我想我会发布我的解决方案,以防其他人有这个问题。
为了解决视口问题,我使用Actions执行moveToElement操作,然后单击:
public void actionsClick(WebElement element){
Actions builder = new Actions(webDriver);
builder.moveToElement(element).click(element).perform();
}
IEDriverServer似乎需要更长的时间来拾取所有的窗口句柄,所以我在做点击后添加了5秒等待到openTab方法:
public void openTab() {
String url = webDriver.getCurrentUrl();
String script = "var a=document.createElement('a');a.target='_blank';a.href='" + url + "';a.innerHTML='open me in a new tab';document.body.appendChild(a);return a";
Object element = getJSExecutor().executeScript(script);
if (element instanceof WebElement) {
WebElement anchor = (WebElement) element;
actionsClick(anchor);
waitFor(5000);
switchBrowserTab();
returnToPreviousBrowserTab();
} else {
throw new RuntimeException("Unable to open tab: " + url);
}
}
然后,如上面的方法所示,为了确保IEDriverServer知道两个窗口/选项卡并可以在它们之间移动,我在单击并等待后添加了switchBrowserTab()和returnToPreviousBrowserTab()方法。使用JavascriptExecutor打开一个新选项卡会让焦点留在原来的选项卡上,这个方法被设置为以焦点再次回到那里结束。如果有人以前没有使用过窗口句柄,这里是我用来切换到新打开的选项卡的方法:
Set<String> handles = webDriver.getWindowHandles();
List<String> handlesList = new ArrayList<String>();
for (String handle : handles) {
handlesList.add(handle);
}
webDriver.switchTo().window(handlesList.get(handlesList.size() - 1));
webDriver.manage().window().maximize();
使用了类似的方法来向后移动,除了我得到当前句柄,然后循环遍历列表以找到它的位置,然后从那里移动到-1句柄。
希望对大家有帮助。
编辑:这适用于IE9和Chrome。未在其他浏览器中测试
- 将菜单项与滚动绑定时出现Jquery错误
- 为什么'滚动到顶部'脚本导致类型错误?jQuery冲突
- 引导表单向导 - 防止在提交 ajax 响应的每个页面表单出现错误时滚动到下一步
- 在 JavaScript 中向下滚动部分的错误
- 正在尝试滚动页面:未捕获类型错误:无法读取属性'top'的未定义
- 滚动字幕未捕获类型错误:无法读取属性'style'的未定义
- 滚动粘贴指令错误
- 滚动功能工作方向错误
- 点击jQuery按钮出现页面滚动错误
- 带有转换比例错误的自定义JavaScript滚动条(jScrollPane)
- 类型错误:使用 requireJs 时未定义滚动到
- UIWebView 在键盘出现时滚动.导致点击偏移错误
- 更改 :后内容时的火狐滚动错误
- 火狐中的滚动错误
- 只在iPad上显示滚动错误
- 多重滚动错误在HTML页面
- 滚动错误在Chrome上的Windows与滑动脚本
- 粘头滚动错误
- fullPage js在IE中滚动错误的高度
- css上的滚动错误chrome/firefox