liv a
liv a

Reputation: 3340

Selenium - how to get runtime generated iframe id

I'm testing a webpage as a blackbox (hard requirement)

the page has a button, on click it calls a function that generates an iframe with a dynamic id, i.e clicking on the same button will create the same frame content but every time with different

<input type="button" value="some txt" onclick="return displayIframe(if_42222440278);">

this creates an iframe like this

<iframe id="6356469882593" class="someClass" scrolling="no" frameborder="0" src="/Pages/somePage.aspx', '', 'width=740px,height=629&rand=6356469882593" allowtransparency="true">

how can I get the iframe id??

these are my tries so far:

attempt 1: resulted in array of 10 objects all null

List<WebElement> iframes = webDriver.findElements(By.id("iframe")); 

attempt 2: resulted in exception that the element doesn't exist

webDriver.switchTo().frame(0)
WebElement editable = webDriver.switchTo().activeElement(); 

any other suggestions?

Upvotes: 0

Views: 3808

Answers (3)

Husam
Husam

Reputation: 1105

Try following code:

List<WebElement> we = driver.findElements(By.xpath("//iframe[@class='someClass']"));
driver.switchTo().frame(we.get(0)); //Switch to iframe.
WebElement activeElement = driver.switchTo().activeElement();
/*Do anything here.
 activeElement.findElement(b).click();*/
driver.switchTo().defaultContent(); //Switch to original frame.

You can identify iframe, switch to it, work in it and switch back to your default content.

Upvotes: 0

Yuvaraj HK
Yuvaraj HK

Reputation: 424

Try

iframeID = driver.findElement(By.cssSelector("iframe[src*='somePage.aspx']")).getAttribute("id");

Upvotes: 0

A Paul
A Paul

Reputation: 8251

Please try below.

List<WebElement> elements = driver.findElements(By.tagname("iframe"))
driver.switchTo().frame(elements.get(0));
//do your stuff
driver.switchTo().defaultContent();

Upvotes: 1

Related Questions