Nested frames let you test web pages that have frames inside other frames. This helps you check content inside each frame correctly.
Nested frames in Selenium Java
driver.switchTo().frame("outerFrameName"); driver.switchTo().frame("innerFrameName"); // perform actions inside inner frame // To go back to main page: driver.switchTo().defaultContent();
Use switchTo().frame() to move into a frame by name, index, or WebElement.
Always switch back to the main page with defaultContent() before switching to another frame.
driver.switchTo().frame("frame1"); driver.switchTo().frame("frame1_1");
driver.switchTo().frame(0); driver.switchTo().frame(1);
WebElement outer = driver.findElement(By.id("outerFrame")); driver.switchTo().frame(outer); WebElement inner = driver.findElement(By.name("innerFrame")); driver.switchTo().frame(inner);
This test opens a page with nested frames, switches to the middle frame inside the top frame, reads the text inside it, prints it, then closes the browser.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class NestedFramesTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://the-internet.herokuapp.com/nested_frames"); // Switch to the top frame driver.switchTo().frame("frame-top"); // Switch to the middle frame inside top frame driver.switchTo().frame("frame-middle"); // Get text inside middle frame WebElement content = driver.findElement(By.id("content")); String text = content.getText(); System.out.println(text); // Switch back to main page driver.switchTo().defaultContent(); } finally { driver.quit(); } } }
Always switch back to the main page with driver.switchTo().defaultContent() before switching to another frame.
Frames can be identified by name, index, or WebElement. Using WebElement is often more reliable.
If you try to find elements inside a frame without switching to it first, Selenium will throw an error.
Nested frames require switching step-by-step into each frame.
Use switchTo().frame() to enter frames and defaultContent() to return to main page.
Always confirm you are in the correct frame before interacting with elements.