</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

How do you handle inner Frames and Adjacent Frames in Selenium?

Use driver.switchTo().frame() to enter frames, and driver.switchTo().defaultContent() to return to the main page. For nested frames, switch to each level sequentially.

Answer

Handling Inner and Adjacent Frames in Selenium

switchTo().frame() moves WebDriver''s focus into an iframe so you can interact with its contents.

Types of frames:

  1. Adjacent frames — Multiple iframes at the same level in the DOM
  2. Inner/nested frames — An iframe inside another iframe

Switching to a frame:

Java
// By index (0-based)
driver.switchTo().frame(0);

// By name or id attribute
driver.switchTo().frame("frameName");
driver.switchTo().frame("frameId");

// By WebElement
WebElement frame = driver.findElement(By.id("myFrame"));
driver.switchTo().frame(frame);

Working with adjacent frames:

Java
// Switch to first iframe and interact
driver.switchTo().frame("frame1");
driver.findElement(By.id("element1")).click();

// Return to main page, then switch to adjacent frame
driver.switchTo().defaultContent();  // Back to main document
driver.switchTo().frame("frame2");
driver.findElement(By.id("element2")).sendKeys("text");

// Return to main page when done
driver.switchTo().defaultContent();

Working with nested (inner) frames:

Java
// Switch to outer frame
driver.switchTo().frame("outerFrame");

// Switch to inner frame (inside outerFrame)
driver.switchTo().frame("innerFrame");

// Interact with inner frame content
driver.findElement(By.id("innerElement")).click();

// Return to parent frame (one level up)
driver.switchTo().parentFrame();

// Or return all the way to main document
driver.switchTo().defaultContent();

Full practical example:

Java
@Test
public void handleFrames() {
    driver.get("https://example.com/page-with-frames");

    // Verify we''re on main page
    Assert.assertEquals(driver.getTitle(), "Main Page");

    // Switch to frame1 (adjacent)
    driver.switchTo().frame("frame1");
    String frameText = driver.findElement(By.tagName("p")).getText();
    Assert.assertEquals(frameText, "Frame 1 content");

    // Move to main page, then frame2 (adjacent)
    driver.switchTo().defaultContent();
    driver.switchTo().frame("frame2");

    // Switch to nested iframe inside frame2
    driver.switchTo().frame("nestedFrame");
    driver.findElement(By.id("nestedBtn")).click();

    // Return to main document
    driver.switchTo().defaultContent();
}

Key methods:

MethodAction
switchTo().frame(0)Switch by index
switchTo().frame("name")Switch by name/id
switchTo().frame(element)Switch by WebElement
switchTo().parentFrame()Go one level up
switchTo().defaultContent()Return to main document

Important: Always return to defaultContent() when done with frames — otherwise subsequent findElement() calls will still search inside the last frame.

Follow AutomateQA

Related Topics