Selenium JavaScript Executor Returning Null When JS Works Fine On Chrome Console
Solution 1:
Looks like I've found the answer to this after some more investigation. The issue was with the driver.switchTo()
commands. The Chrome console was interpreting the code on the default page level where Selenium was looking at the DOM only from 'EmailMessage'
up. These were left in there as a result of previously using SendKeys()
.
Reordering the lines to the following allowed the elements in the iframe to be checked with their explicit waits and then the JS to be run on the page level. Another solution would be to change the JS string to begin at the document.body...
level. My fix is as follows:
JavascriptExecutor js = (JavascriptExecutor) driver;
driver.switchTo().frame(emailBodyID);
wait.until(ExpectedConditions.visibilityOfElementLocated(emailBodyTag));
wait.until(ExpectedConditions.elementToBeClickable(emailBodyTag));
driver.switchTo().defaultContent();
js.executeScript("document.getElementById('EmailMessage').contentWindow.document.body.appendChild(document.createTextNode('testText'));");
Fairly simple and a bit obvious looking back at it (isn't everything though), but for anyone wanting to switch SendKeys()
with some JS in an iframe (or perform any other action involving JS and changing scopes with iframes in Selenium), it's something that can be a bit of sneaky issue.
Post a Comment for "Selenium JavaScript Executor Returning Null When JS Works Fine On Chrome Console"