简体   繁体   中英

Cannot read property 'setValue' of undefined error. How to type text in codeMirror element using Selenium WebDriver and Java?

I am trying to enter text in textarea. As I know this field is CodeMirror. This is my code:

{...

WebElement scriptField = 

this.getDriver().findElement(By.cssSelector(".CodeMirror-line>span"));

JavascriptExecutor js = (JavascriptExecutor) this.getDriver();

String query = "text";

js.executeScript("arguments[0].CodeMirror.setValue(\""+ query +"\");", scriptField);

}

And I have this error at last line of my code:

org.openqa.selenium.WebDriverException : unknown error: Cannot read property 'setValue' of undefined

I am not sure to which webelement I should refer to in scriptField variable. When I am typing text (manually) it appears in this element: ".CodeMirror-line>span" . So Am I correct?

There is fragment of my DOM on attached picture.

在此处输入图片说明

Once you have the WebElement, scriptField in this case, simply use sendKeys() method.

WebElement scriptField = this.getDriver().findElement(By.cssSelector(".CodeMirror-line>span"));
scriptField.sendKeys("your text");

You can also clear the field before adding your text in it.

WebElement scriptField = this.getDriver().findElement(By.cssSelector(".CodeMirror-line>span"));
scriptField.clear();
scriptField.sendKeys("your text");

如果要在span元素内设置实际文本,请尝试以下操作:

js.executeScript("arguments[0].innerText = " + query + ";", scriptField);

To change the existing text to myText use the following code block :

WebElement scriptField = this.getDriver().findElement(By.cssSelector("pre.CodeMirror-line>span"));
JavascriptExecutor jse = (JavascriptExecutor) this.getDriver();
String js = "arguments[0].innerHTML='myText';";
jse.executeScript(js, scriptField);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM