Selenium: Unable to access iframe and data inside it

I have HTML code like this for an iframe:

<iframe class="class1" prio="0" title="Details" type="detail" source="/something/somepage.aspx" style="display:none" frameborder="0"></iframe>

This frame has a menu, text input and buttons inside it as it opens a popup on the current page. Popup gets its data from the source page as above.

I tried different approaches i.e. by finding index manually of the iframe and then display its title to see if I am at the right frame but had no luck with it.

I am trying to type data in the form in iframe and then get back to the main page but am being clueless. Please help!


Solution 1:

SwitchTo() method takes index, name or frame element, so you can try use name or frame element.

//find the frame by class/title/type/source
IWebElement detailFrame = driver.FindElement(By.XPath("//iframe[@class='class1']"));
driver.SwitchTo().Frame(detailFrame);

//alternatively, find the frame first, then use GetAttribute() to get frame name
IWebElement detailFrame = driver.FindElement(By.XPath("//iframe[@class='class1']"));
driver.SwitchTo().Frame(detailFrame.GetAttribute("name"));

//you are now in iframe "Details", then find the elements you want in the frame now
IWebElement foo = driver.FindElement(By.Id("foo"));
foo.Click();

//switch back to main frame
driver.SwitchTo().DefaultContent();

Solution 2:

Did you try (java code):

driver.switchTo().frame("iFrameName");

driver.findElement(By.id("formOne")).click();
driver.findElement(By.id("formOne")).sendKeys("abc");