Skip to content
CodeKruPro

Return from a frame to the main page

Automation taskMediumAsked in: Accenture, Capgemini, Cognizant, Infosys, TCS, Wipro

"After working inside an iframe, your next step on the main page fails. Why?" The driver is still inside the frame and cannot see the main page. Switch back to the default content, the top-level document.

Switch Between Frames and Default Content

Switch Between Frames and Default Content

Key frame navigation methods:

  • driver.switchTo().frame() - switch to a frame
  • driver.switchTo().parentFrame() - go up one level
  • driver.switchTo().defaultContent() - go back to the main page

Full Page Frame Structure:

<!-- Default Content (main page) -->
<h2>Frames</h2>

<iframe id="frame1">              <!-- switchTo().frame("frame1") -->
  <h1>CodeKru</h1>
</iframe>

<iframe name="nestedFrame">       <!-- switchTo().frame("nestedFrame") -->
  <h2>Parent frame</h2>
  <iframe>                        <!-- switchTo().frame(0) from parent -->
    <h3>Child frame</h3>
  </iframe>
</iframe>

defaultContent() always returns to the main page. parentFrame() goes up one level.

Task:

  1. Navigate to https://testkru.com/Interactions/Frames
  2. Get the main page heading
  3. Switch to frame1, get its h1 text
  4. Switch back to default and get the heading again to verify

Expected output:

Main page: Frames
Frame content: CodeKru
Back to main: Frames