How to use SendKeys(webdriver) command in Rich Tex

2019-01-14 20:10发布

问题:

I'm facing the following problem.I can not type text in iframe in which there is a text editor:Here is the html:

<iframe class="cke_wysiwyg_frame cke_reset" frameborder="0" style="width: 100%;  height: 100%;" aria-describedby="cke_39" title="Текстов редактор за форматиран текст,description1" src="" tabindex="0" allowtransparency="true">
<!DOCTYPE html>
<html lang="bg" dir="ltr">
<head>
<body class="cke_editable cke_editable_themed cke_contents_ltr" contenteditable="true" spellcheck="false">
<p>
<br>
</p>
</body>
</html>
</iframe>

Here is what I have done so far,but the test passed successfully and no text is writen in the text editor.May be the solution is with Javascript executor but I'm not familiar with it.

WaitTool.waitForElementPresent(Browser.instance, By.tagName("iframe"), 10);
WebElement iframe = Browser.instance.findElement(By.tagName("iframe"));
Browser.instance.switchTo().frame(iframe);
WebElement description=Browser.instance.findElement(By.xpath("//body[@class='cke_editable cke_editable_themed cke_contents_ltr']"));
description.click();
description.sendKeys("someText");
Browser.instance.switchTo().defaultContent();

Thanks in Advance!

回答1:

There are multiple ways of doing it. Here's an article you might want to have a look.

Test WYSIWYG editors using Selenium WebDriver

  • Send keys directly

This approach is the one you have tried and didn't work. Please try make sure your locators to <iframe> and <body> are correct. Otherwise I'd suggest using JavaScriptExecutor for more stable solutions.

  • Set innerHTML
WaitTool.waitForElementPresent(Browser.instance, By.className("cke_wysiwyg_frame"), 10);
WebElement iframe = Browser.instance.findElement(By.className("cke_wysiwyg_frame"));
Browser.instance.switchTo().frame(iframe);

WebElement description = Browser.instance.findElement(By.cssSelector("body"));
(JavascriptExecutor)Browser.instance.executeScript("arguments[0].innerHTML = '<h1>Set text using innerHTML</h1>'", description);
  • Use CKEditor's native API
// no need to switch iframe
(JavascriptExecutor)Browser.instance.executeScript("CKEDITOR.instances.ckeditor.setData('<h1>Native API text</h1> Editor')");