About this lesson
Switch to a frame by name in Selenium Java
Learn Selenium JavaAdvancedFrames
How it works
The name attribute is the classic way to label a frame, and switchTo().frame() called with a string checks it alongside the id. The second iframe on the Frames page has name="nestedFrame" and id="frame2", so either string switches into it.
Names matter most for frames that have no id, which is common in older pages and generated widgets. When a frame has neither, you fall back to its index or to the frame element itself, both shown in the next lesson.
Inside a frame, locators work on the frame's own document only. This frame's document has an h2 and a child iframe of its own, and that child's contents are not searchable from here.
About the assignment
The frame named nestedFrame holds an h2 heading and another frame. You switch in by name, read the h2, and switch back to the main page.
What you will do
- Pass the frame's name to
driver.switchTo().frame(). - Find the
h2and print its text after the label from the expected output. - Return to the main page with
defaultContent().
Common mistakes
Searching for the child's h3 from here
The
h3lives one frame deeper. Looking for it while you are innestedFramethrowsNoSuchElementException.Misspelling the name
Names are case-sensitive. A wrong name throws
NoSuchFrameExceptionwith "No frame element found by name or id".Finding the h2 before switching
The main page has its own
h2, so the lookup succeeds and prints the main heading instead of the frame's.
In a real test suite
Legacy admin tools and reporting dashboards often split the screen into named frames such as a menu frame and a content frame. Tests switch by those names, which are usually more stable than positions.
Lesson 44 switched by id. Lesson 46 goes one level deeper into the child frame inside this one.
Related lessons
- Switch to Frame by IDSwitch by id, and handle two frames with the same id.
- Handle Nested FramesReach the frame inside this frame.
- Find Element by Name
nameattributes, used here to identify a frame.
To try one of these calls on any page without a task, open the Online Selenium Java Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Interactions/Frames");
// TODO: Switch to frame by name "nestedFrame"
// TODO: Find h2 and print its text
// TODO: Switch back to default content
driver.quit();
}
}