I am attempting to input some text into a text box within an iframe using Selenium and ChromeDriver (Java) and encountering the following error in my stack trace:
org.openqa.selenium.WebDriverException: unknown error: Cannot read property 'contentWindow' of null
Even after confirming that the entire DOM is loaded with a breakpoint, the error persists. It works fine when testing the JS code in Chrome's console at the same breakpoint but fails when proceeding through the test. This suggests a discrepancy between how the JS is executed by Selenium versus Chrome's console.
This particular section of the DOM is relevant:
<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>
Executing the following JS code in Chrome's console:
document.getElementById('EmailMessage').contentWindow.document.body.appendChild(document.createTextNode('testText'));
Correctly updates the inner HTML between the body tags as expected:
<body contenteditable="true">testText</body>
However, running the equivalent code in Java causes it to fail, resulting in the mentioned error. Below is the relevant part of my Java 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();
Any insights on what might be causing this? I have tested variations like contentDocument.body
without success. As an alternative to sendKeys()
, due to compatibility issues with older versions of ChromeDriver, I attempted this approach even with the latest version locally, where it still failed consistently indicating a broader issue rather than environment-specific.
Thanks, Darwin.