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:
org.openqa.selenium.WebDriverException: unknown error: Cannot read property 'contentWindow' of null
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 js.executeScript 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.
Here is the part of the DOM I'm looking at:
<div class="container">
<iframe class="rich-text-area" id="EmailMessage">
#document
<html>
<head>
<link rel="stylesheet" type="text/css" href="/static/css/rich-text-editor.css">
<link rel="stylesheet" type="text/css" href="/rest/email/css">
</head>
<body contenteditable="true"></body>
</html>
</iframe>
<textarea class="code" aria-hidden="true" id="emailSource" style="display: none;"> </textarea>
</div>
When running my JS in the Chrome console which is:
document.getElementById('EmailMessage').contentWindow.document.body.appendChild(document.createTextNode('testText'));
I get the desired result which is inner HTML between the body tags as such:
<body contenteditable="true">testText</body>
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:
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();
Any idea what's going on here? I've tried contentDocument.body as well. Same results in Chrome and Selenium. I'm using this as an alternative to sendKeys() as I'm forced to run an older version of ChromeDriver for this test that has broken support for sendKeys() 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.
Cheers, Darwin.