title: Selenium Executing JavaScript within the page
body: <p>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. </p>
  
  <p>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: </p>
  
  <pre><code>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();
  
  }
  </code></pre>
  
  <p>The result of this code is always that <code>document.querySelector</code> is undefined. </p>
  
  <p>Alternatively I also tried passing a second argument to <code>js.executeScript</code>:</p>
  
  <pre><code>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();
  
  }
  </code></pre>
  
  <p>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</p>
  
  <p>I also found that it was possible to use BrowserBot: <code>this.browserbot.getUserWindow()</code> or <code>selenium.browserbot.getUserWindow()</code> but it doesn't seem to work anymore.</p>
  
  <p>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: <code>document.getSelection()</code>. I can consider alternative ways to get the same result.</p>
  
  <p>What am I doing wrong? How can I fix this?</p>