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?
driver.switchTo().frame(iframe);
just before ofdriver.close()
I get an empty list. Changing the selector to this:Object o = js.executeScript("return arguments[0].querySelectorAll('*')", body);
Object o is made of a number of elements likeo = [[org.openqa.selenium.remote.RemoteWebElement@5d21e41 -> unknown locator]]
– john locke Jun 25 at 4:42o = []
– john locke Jun 25 at 4:48