sharan
sharan

Reputation: 213

How to select new IFrame using Selenium WebDriver?

I wanted to select an Iframe and Enter values in the Body . I am trying with the below code.

HTML code:

 <iFrame id="4564654_content_ifr">
     <html>
       <head>
         <body id="tiny">
             <div aria-lable="New Compose body">
                 <br>
             </div>
         </body>
       </head>
      </html>
  </iFrame>

Selenium code:

    driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(@id,'content_ifr')]")));
driver.findElement(By.xpath("//*[@id='tiny']/div[1]")).sendKeys("Happy New IFrame");

But I could not able to enter values.

Can anybody help me with this?

Upvotes: 1

Views: 3040

Answers (3)

Naresh Reddy
Naresh Reddy

Reputation: 1

List<WebElement> iframeElements= driver.findElements(By.tagName("iframe"));
System.out.println("The total number of iframes are " + iframeElements.size());
driver.switchTo().frame(0);
Thread.sleep(3000);
System.out.println("it is on frame1");

Upvotes: 0

Raghuveer
Raghuveer

Reputation: 115

Try the below May help you.

WebElement sg= driver.findElement(By.xpath("//iframe[@id='4564654_content_ifr']"));
                driver.switchTo().frame(sg);

Upvotes: 0

Yi Zeng
Yi Zeng

Reputation: 32845

Instead of sending keys, you can set innerHTML directly.

driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(@id,'content_ifr')]")));

WebElement body = driver.findElement(By.cssSelector("body"));
(JavascriptExecutor)driver.executeScript("arguments[0].innerHTML = 'Happy New IFrame'", body);

If you are testing some kind of WYSIWYG editors like TinyMCE, feel free to have a look at this article:

Test WYSIWYG editors using Selenium WebDriver

Then you might be able to set content through editor's API directly. It's known to have issues with sendKeys in Firefox, but should be fine with Chrome or PhantomJS.

Upvotes: 4

Related Questions