About this lesson
Switch back from a frame in Selenium Java with defaultContent() and parentFrame()
Learn Selenium JavaAdvancedFrames
How it works
driver.switchTo().defaultContent() returns to the top-level document, however deep you are. driver.switchTo().parentFrame() goes up exactly one level, so from the child frame on this page it returns you to nestedFrame, and a second call returns you to the main page. At the top it does nothing and throws nothing.
Switching out is part of the test, not tidying. While the driver is inside a frame, every findElement() searches only that frame, so a step that expects main-page elements fails with NoSuchElementException if an earlier step forgot to switch back.
The main page and frame1 each have a heading, which makes this page a clear way to see where the driver is: read the heading, switch, read again.
About the assignment
You read the main page's h2, step into frame1 to read its h1, and step back out to read the h2 again. The repeated read proves the driver really returned to the main page.
What you will do
- Before switching, read the main page's
h2and print it after the labelMain page:. - Switch into
frame1, read itsh1and print it after the labelFrame content:. - Call
defaultContent(). - Read the
h2again and print it after the labelBack to main:.
Common mistakes
Reusing the first h2 element
Printing a
Stringsaved from the first read proves nothing about where the driver is. Find the heading again after switching back.Using parentFrame() to go to the top from deep nesting
It climbs one level per call. From two frames down you need two calls, or one
defaultContent().Forgetting to switch back at all
Inside
frame1there is noh2, so the last lookup throwsNoSuchElementException.
In a real test suite
Many teams switch back in a finally block or let page objects switch in and out inside each method, so a failed step inside a frame does not leave every later step searching the wrong document.
Lesson 46 went down two levels. Lesson 48 moves from frames to browser windows, starting with the handle that identifies each one.
Related lessons
- Switch to Frame by IDEnter
frame1by id. - Handle Nested FramesNested frames, where
parentFrame()is most useful. - Handle Multiple WindowsSwitch between windows, the other kind of context switch.
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: Get main page h2 heading
// TODO: Switch to frame1, get h1 text
// TODO: Switch to default content, get h2 heading again
driver.quit();
}
}