Selenium JavascriptExecutor on IE9 results in 'element was not scrolled into the viewport' error

落爺英雄遲暮 提交于 2019-12-06 09:31:52
user2362947

I had been having this difficulty in IE9 in a parallels VM. These are the two lines that made the whole thing work...

Actions builder = new Actions(webDriver);
builder.moveToElement(element).click(element).perform();

Scrolls the element into view then clicks it.

Managed to resolve the viewport issue & get the IEDriverServer to interact properly with both windows after a little coaxing so thought I'd post my solution in case anyone else has this problem.

To resolve the viewport problem, I used Actions to do a moveToElement then click:

public void actionsClick(WebElement element){
    Actions builder = new Actions(webDriver);
    builder.moveToElement(element).click(element).perform();
}

The IEDriverServer seems to take a little longer to pick up all the window handles, so I added a 5 second wait into the openTab method after doing the click:

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);
    }
}

Then, as shown in the method above, to ensure the IEDriverServer is aware of both windows/tabs and can move between them, I added switchBrowserTab() and returnToPreviousBrowserTab() methods after clicking and waiting. Using the JavascriptExecutor to open a new tab will leave focus in the original tab and this method is set up to end with focus back in there again. In case anyone hasn't used the window handles before, here is the method I'm using for switching to the newly opened tab:

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

A similar approach is used to move back except I get the current handle, then loop through the list to find its position, then move to the handle that is -1 from there.

Hope this is helpful.

Edit: this works in IE9 and Chrome. Not tested in other browsers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!