How to switch back from a frame to default in Selenium Webdriver?

SeleniumAutomation TestingTesting Tools

We can switch back from a frame to default in Selenium webdriver using the switchTo().defaultContent() method. Initially, the webdriver control remains on the main web page.

In order to access elements within the frame, we have to shift the control from the main page to the frame with the help of the switchTo().frame and pass the frame name/id or webelement of the frame as a parameter to that method.

Finally, again we can switch the control to the main page with the switchTo().defaultContent() method. A frame is identified in the html code with the tag names – frame, iframe or frameset.

Let us identify the text Iframe which is inside a frame and the text click on the below link − which is outside a frame

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class FrameDefaultSwitch{
public static void main(String[] args) {
   System.setProperty("webdriver.gecko.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
   WebDriver driver = new FirefoxDriver();
   //implicit wait
   driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
   //URL launch
   driver.get("http://www.uitestpractice.com/Students/Switchto");
   // switch to frame
   driver.switchTo().frame("iframe_a");
   //identify element inside frame
   WebElement d = driver.findElement(By.tagName("h1"));
   System.out.println("Text inside frame: " + d.getText());
   //switch to default
   driver.switchTo().defaultContent();
   //identify element outside frame
   WebElement e = driver.findElement(By.tagName("h3"));
   System.out.println("Text outside frame: " + e.getText());
   driver.quit();}
}

Output

raja
Published on 06-Apr-2021 08:34:11
Advertisements