How to Handle iframe in Selenium with Java?
Last Updated :
29 Jul, 2025
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:
- Switch to the iframe: Selenium provides a way to switch to an iframe either by its index, name, or WebElement.
- Interact with elements inside the iframe: Once switched, you can interact with the elements inside the iframe as you would on the main page.
- 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 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
IFrames
Similar Reads
Software Testing Tutorial Software testing is an important part of the software development lifecycle that involves verifying and validating whether a software application works as expected. It ensures reliable, correct, secure, and high-performing software across web, mobile applications, cloud, and CI/CD pipelines in DevOp
10 min read
What is Software Testing? Software testing is an important process in the Software Development Lifecycle(SDLC). It involves verifying and validating that a Software Application is free of bugs, meets the technical requirements set by its Design and Development, and satisfies user requirements efficiently and effectively.Here
11 min read
Principles of Software testing - Software Testing Software testing is an important aspect of software development, ensuring that applications function correctly and meet user expectations. From test planning to execution, analysis and understanding these principles help testers in creating a more structured and focused approach to software testing,
3 min read
Software Development Life Cycle (SDLC) Software Development Life Cycle (SDLC) is a structured process that is used to design, develop, and test high-quality software. SDLC, or software development life cycle, is a methodology that defines the entire procedure of software development step-by-step. The goal of the SDLC life cycle model is
8 min read
Software Testing Life Cycle (STLC) The Software Testing Life Cycle (STLC) is a process that verifies whether the Software Quality meets the expectations or not. STLC is an important process that provides a simple approach to testing through the step-by-step process, which we are discussing here. Software Testing Life Cycle (STLC) is
7 min read
Types of Software Testing Software testing is a important aspect of software development life-cycle that ensures a product works correctly, meets user expectations, and is free of bugs. There are different types of software testing, each designed to validate specific aspects of an application, such as functionality, performa
15+ min read
Levels of Software Testing Software Testing is an important part of the Software Development Life Cycle which is help to verify the product is working as expected or not. In SDLC, we used different levels of testing to find bugs and errors. Here we are learning those Levels of Testing in detail.Table of ContentWhat Are the Le
4 min read
Test Maturity Model - Software Testing The Test Maturity Model (TMM) in software testing is a framework for assessing the software testing process to improve it. It is based on the Capability Maturity Model(CMM). It was first produced by the Illinois Institute of Technology to assess the maturity of the test processes and to provide targ
8 min read
SDLC MODELS
TYPES OF TESTING