Open In App

How to Handle iframe in Selenium with Java?

Last Updated : 29 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Many web applications use iframes for embedding external login forms, advertisements, or even Google Maps, making it essential to handle them properly in automation scripts. For example, testing a web form that is located inside an iframe, Selenium must switch to that iframe before interacting with the elements in the iframe.

Key Concepts:

Here are the essential methods and concepts for handling iFrames in Selenium:

  • iFrame: An HTML element (<iframe>) that embeds another document within the current webpage.
  • switchTo().frame(): Switches the WebDriver's focus to a specific iframe, allowing interaction with its elements.
  • switchTo().defaultContent(): Switches the WebDriver's focus back to the main document.
  • switchTo().parentFrame(): Switches to the parent frame of the current iframe, useful for nested iframes.
  • WebDriverWait: Used to wait for an iframe to be available before switching to it.
  • findElement() / findElements(): Used to locate elements within an iframe after switching to it.

Switching to an iframe in Selenium

1. By Index: If there are multiple iframes on a page, you can switch to a specific iframe by its index. The index starts at 0 for the first iframe.

driver.switchTo().frame(0);  // Switch to the first iframe

2. By Name or ID: If the iframe has a name or id attribute, you can switch to it using the name or ID directly.

driver.switchTo().frame("iframeName");  // Switch to iframe with name "iframeName"

3. By WebElement: If you have a WebElement locator for the iframe, you can switch to it by passing the WebElement to switchTo().frame().

WebElement iframeElement = driver.findElement(By.id("iframeId"));
driver.switchTo().frame(iframeElement); // Switch to iframe using the WebElement

Interacting with iframe

After switching to the iframe, you can interact with the elements inside it.

Java
// Switch to the iframe first
driver.switchTo().frame("iframeId");

// Find and interact with elements inside the iframe
WebElement inputField = driver.findElement(By.id("username"));
inputField.sendKeys("testuser");

// Submit the form
WebElement submitButton = driver.findElement(By.id("submit"));
submitButton.click();

Switching Back to the main page

After interacting with the iframe, you’ll need to switch back to the main page.

driver.switchTo().defaultContent();  // Switch back to the main page

Handling Nested iFrames

In some cases, an iframe might be nested within another iframe. In such situations, you need to switch to the parent iframe first, then the child iframe.

// Switch to the parent iframe
driver.switchTo().frame("parentIframe");

// Switch to the child iframe within the parent iframe
driver.switchTo().frame("childIframe");

Prerequisite

Complete the requirements below to handle iframe in Selenium:

  • Install JDK (Java Development Kit).
  • Install Eclipse.
  • Add Selenium WebDriver dependencies in pom.xml.
  • Maven or Gradle for dependency management.
  • TestNG for running tests.

Example of Handling iframe in Selenium

Below is complete example where we handle an iframe, which include BaseTest class that initializes the WebDriver:

BaseTest.java

Java
package io.learn;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

public class BaseTest {

    protected WebDriver driver;
    

    // Set up the ChromeDriver
    @BeforeMethod
    public void setup() {
        // Set the path to your chromedriver executable
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\change the path of the ChromeDriver\\drivers\\chromedriver.exe");
        
        // Initialize the ChromeDriver
        driver = new ChromeDriver();
        
    }

    // Close the browser after each test
    @AfterMethod
    public void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

Steps for Handling iframes in Selenium

To handle iframes in Selenium, follow these steps:

  1. Switch to the iframe: Selenium provides a way to switch to an iframe either by its index, name, or WebElement.
  2. Interact with elements inside the iframe: Once switched, you can interact with the elements inside the iframe as you would on the main page.
  3. Switch back to the main page: After completing actions within the iframe, it’s necessary to return focus to the main page.

Here is a complete example where we handle an iframe, interact with elements inside it, and return to the main page.

Java
package io.learn.iframes;

import static org.assertj.core.api.Assertions.assertThat;

import java.time.Duration;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

import io.learn.BaseTest;

public class IFramesTest extends BaseTest {

    @Test
    void testIFrames() {
        driver.get(
                "https://bonigarcia.dev/selenium-webdriver-java/iframes.html");

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        wait.until(ExpectedConditions
                .frameToBeAvailableAndSwitchToIt("my-iframe"));

        By pName = By.tagName("p");
        wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(pName, 0));
        List<WebElement> paragraphs = driver.findElements(pName);
        assertThat(paragraphs).hasSize(20);

        driver.switchTo().defaultContent();
        assertThat(driver.findElement(By.xpath("//h5")).getText()).isEqualTo("Practice site");
    }

    @Test
    void testFrames() {
        driver.get(
                "https://bonigarcia.dev/selenium-webdriver-java/frames.html");

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        String frameName = "frame-body";
        wait.until(ExpectedConditions
                .presenceOfElementLocated(By.name(frameName)));
        driver.switchTo().frame(frameName);

        By pName = By.tagName("p");
        wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(pName, 0));
        List<WebElement> paragraphs = driver.findElements(pName);
        assertThat(paragraphs).hasSize(20);
        driver.switchTo().defaultContent();
    }
}

Output:

output-of-handling-iframes-
Output of Handling Iframes

Selenium provides functionality to switch between the main document and iframes, allowing you to access and manipulate iframe content just like you would with regular elements on the page. If you don't switch to the iframe before interacting with the elements inside it, Selenium won't be able to find them, and you might encounter errors like NoSuchElementException.


Advanced Interactions with WebDriver
Visit Course explore course icon
Video Thumbnail

Advanced Interactions with WebDriver

Video Thumbnail

IFrames

Article Tags :

Similar Reads