title: Selenium JavaScript executor returning null when JS works fine on Chrome console
body: <p>I'm trying to add some text to a text box in an iframe using Selenium + ChromeDriver (Java-driven) and I'm getting the following error in my stack trace:</p>
  
  <p><code>org.openqa.selenium.WebDriverException: unknown error: Cannot read property 'contentWindow' of null</code></p>
  
  <p>I've used a breakpoint to ensure the entire DOM is loaded so that doesn't appear to be the issue. I've also tested my JS in the Chrome console while at the breakpoint on the <code>js.executeScript</code> line and it works fine. As soon as I step forward through my test, though, it fails with the same error. It appears to be some discrepancy between how the JS is being run through Selenium as opposed to how it is being run through Chrome's console.</p>
  
  <p>Here is the part of the DOM I'm looking at:</p>
  
  <pre><code>&lt;div class="container"&gt;
   &lt;iframe class="rich-text-area" id="EmailMessage"&gt;
    #document
     &lt;html&gt;
      &lt;head&gt;
       &lt;link rel="stylesheet" type="text/css" href="/static/css/rich-text-editor.css"&gt;
       &lt;link rel="stylesheet" type="text/css" href="/rest/email/css"&gt;
       &lt;/head&gt;
       &lt;body contenteditable="true"&gt;&lt;/body&gt;
     &lt;/html&gt;
   &lt;/iframe&gt;
   &lt;textarea class="code" aria-hidden="true" id="emailSource" style="display: none;"&gt;            &lt;/textarea&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>When running my JS in the Chrome console which is:</p>
  
  <p><code>document.getElementById('EmailMessage').contentWindow.document.body.appendChild(document.createTextNode('testText'));</code></p>
  
  <p>I get the desired result which is inner HTML between the  body tags as such:</p>
  
  <p><code>&lt;body contenteditable="true"&gt;testText&lt;/body&gt;</code></p>
  
  <p>However, when running it using the following code, it's blowing up and giving me the error noted above. Here is the part of my Java code that runs this:</p>
  
  <pre><code>JavascriptExecutor js = (JavascriptExecutor) driver;
  driver.switchTo().frame(emailBodyID);
  wait.until(ExpectedConditions.visibilityOfElementLocated(emailBodyTag));
  wait.until(ExpectedConditions.elementToBeClickable(emailBodyTag));
  js.executeScript("document.getElementById('EmailMessage').contentWindow.document.body.appendChild(document.createTextNode('testText'));");
  driver.switchTo().defaultContent();
  </code></pre>
  
  <p>Any idea what's going on here? I've tried <code>contentDocument.body</code> as well. Same results in Chrome and Selenium. I'm using this as an alternative to <code>sendKeys()</code> as I'm forced to run an older version of ChromeDriver for this test that has broken support for <code>sendKeys()</code> in iframes. I've tried this code on my local machine with the latest ChromeDriver and it's still failing so it doesn't appear to be an environmental issue.</p>
  
  <p>Cheers,
  Darwin.</p>