Selenium + Java · Lesson 21 of 44

0/44 done

Module 21: Frames

21. Frame Switching & Nested iframe Automation

15 minlesson

Your task

Implement executeInFrame:

  1. Accept WebDriver driver, WebElement frame, and Runnable action.
  2. Switch to frame, execute action.run(), and in a finally block call driver.switchTo().defaultContent().

Write it in the editor, then press Check answer (Ctrl + Enter).

Switching into iframes

java
// Method 1: By WebElement (Recommended)
WebElement frameElement = driver.findElement(By.id("payment-frame"));
driver.switchTo().frame(frameElement);

// Interact inside the frame:
driver.findElement(By.id("card-number")).sendKeys("4242 4242 4242 4242");

// Always switch back to the main page:
driver.switchTo().defaultContent();

// Switching to parent frame from nested iframe:
driver.switchTo().parentFrame();

Key Takeaways & Walkthrough Summary

iframes are separate embedded HTML documents. In Selenium, you must explicitly switch WebDriver context into the frame to locate elements inside it, and switch back to default content afterwards. Let's master iframe switching!

Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why does findElement fail when looking for an element inside an iframe?

WebDriver searches only the current browsing context. If you haven't called driver.switchTo().frame(), it cannot see elements inside iframes.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip