Selenium Executing JavaScript within the page

冷暖自知 提交于 2019-12-13 01:24:49

问题


I am using Selenium 2 and I need to execute some JavaScript in the page as part of the tests. I saw various examples on the web, no one of them seem to work.

What I need to do it's this: after the user interacts with the web page, pressing buttons, adding text etc, I need to get the user selection, which is raw javascript is:

public void jsTest() {
    WebDriver driver = new FirefoxDriver();
    driver.navigate().to("http://www.tinymce.com/");
    WebElement iframe = driver.findElement(By.tagName("iframe"));

    driver.switchTo().frame(iframe);

    WebElement body = driver.findElement(By.xpath("//body"));
    body.sendKeys("Write something");
    JavascriptExecutor js;
    js = (JavascriptExecutor)driver;
    Object o = js.executeScript("return document.querySelector('iframe')");
    System.out.println("o = " + o);


    driver.close();
    driver.quit();

}

The result of this code is always that document.querySelector is undefined.

Alternatively I also tried passing a second argument to js.executeScript:

public void jsTest() {
    WebDriver driver = new FirefoxDriver();
    driver.navigate().to("http://www.tinymce.com/");
    WebElement iframe = driver.findElement(By.tagName("iframe"));

    driver.switchTo().frame(iframe);

    WebElement body = driver.findElement(By.xpath("//body"));
    body.sendKeys("Write something");
    JavascriptExecutor js;
    js = (JavascriptExecutor)driver;
    Object o = js.executeScript("return arguments[0].querySelector('iframe')", iframe);
    System.out.println("o = " + o);


    driver.close();
    driver.quit();

}

And in this case I get: org.openqa.selenium.StaleElementReferenceException: Element belongs to a different frame than the current one - switch to its containing frame to use it

I also found that it was possible to use BrowserBot: this.browserbot.getUserWindow() or selenium.browserbot.getUserWindow() but it doesn't seem to work anymore.

The reason I am doing this it's that I need to get the user selection while typing, for example cursor position, and this is possible in plain JavaScript with: document.getSelection(). I can consider alternative ways to get the same result.

What am I doing wrong? How can I fix this?

来源:https://stackoverflow.com/questions/24399302/selenium-executing-javascript-within-the-page

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