Iframe handling in Selenium

Iframe means an inline frame, which is an HTML document embedded inside another HTML document on a particular website. It is specified by <iframe> tag.  We need to switch to an iframe to interact with elements inside it.

image001

To switch between iframes, we can use the following methods:

  • Switch to frame by index

To switch to frame by index, we need to know the index of an Iframe, i.e. the position of iframe in that HTML page.

Suppose we want to switch to the first iframe on a webpage, then we can do it as follows:

driver.get(“http://webdemo.saksoft.com/360logica/blog/”);

List<WebElement> iframes_element = driver.findElements(By.tagName(“iframe”));

int iframes =  iframes_element.size();

System.out.println(“The total number of iframes are ” + iframes);

driver.switchTo().frame(0);

  • Switch to frame by id

To switch to frame by id, we can use the id attribute as follows:

image002

driver.switchTo().frame(“twitter-widget-1”);

Here twitter-widget-1 is the id as shown in the image above.

  • Switch to frame by name

To switch to frame by name, we can use the name attribute as follows:

Understanding Selenium WebDriver API Commands (Part 5)

driver.switchTo().frame(“google_conversion_frame”);

Here google_conversion_frame is the name as shown in the image above.

  • Switch to frame by WebElement

We can switch to frame by passing the iframe WebElement as follows:

driver.switchTo().frame(driver.findElement(By.name(“google_conversion_frame”)));

After performing all the actions within an iframe, you can switch to the default window using the following command:

driver.switchTo().defaultContent();

Also Read: Understanding Selenium WebDriver API Commands (Part 4)