Open In App

How to Handle iframe in Selenium with Java?

Last Updated : 09 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to discuss how to handle the iframe in Selenium with Java. The following 6 points will be discussed.

Let’s start discussing each of these topics in detail.

What are iframes in Selenium?

Displaying a webpage as a part of another webpage this parameter we called iframe. If the element is present on the main page then we can directly interact and we can perform the actions but when the element is present on iframe we can not directly interact with those elements. In such cases, we need to change the focus of selenium from the main page to the iframe.

Difference between frame and iframe in Selenium

Normally frames are used for the horizontally or vertically splitting of a webpage. So with the help of a frame, we can split a webpage into multiple sections. frames are the part of the page. Whereas iframes are generally used to insert the contents from other sources. Iframe sets the URL of the website to be displayed as a part of another webpage, and the width and height of the iframe can be set to determine how much of the website should be displayed.

Steps to Identify a Frame on a Page?

There are some methods from which we can identify if there is any iframe present on the webpage or not.

Step.1: Search the iframe on the inspection box

iframeInsp1
Search the iframe on the inspection box


Step.2: Right-click on that web element

RightCiframe1
Right-click on that web element


Step.3: Through view page source

iframePages
Through view page source


How to Switch Over the Elements in iframes using Web Driver Commands

After identifying the iframe if we need to handle a web element that is present on the iframe, in such cases, we need to change the focus of selenium from the main page to the iframe. There are three different ways to shift the focus of selenium from the main page to the iframe.

1. With the help of the index 

Syntax:

driver.switchTo().frame(index);
the index always starts from zero (0,1,2,3,…..)

2. With the help of id/name

Syntax:

driver.switchTo().frame(“idvalue/namevalue”);
here we need to identify the id value or name value from the HTML codes of the iframe.

3. With the help of web element

Syntax:

driver.switchTo().frame(webelement);
here we need to declare a webelement by using attributes of iframe.

How to Switch Back to the Main iframe

Suppose we need to change the focus of selenium from iframe to the main page or parent iframe for which there are two different ways.

  • driver.switchTo().parentFrame(); – We use this method to change the focus of selenium from one iframe to parent iframe (previous iframe)
  • driver.switchTo().defaultContent(); – We use this method to change the focus of selenium from one iframe to the main page.

For performing the automation we will create a webpage by using HTML. Here are the HTML codes for creating a webpage with an iframe.

HTML
<!DOCTYPE html>
<html>
   <head>
      <style>
         .gfg 
         {width:200px}
         .gfgiframe
         {width:400px;
         height:200px;
         background-color:#98FB98}
      </style>
   </head>
   <body>
      <center>
         <h1 style="color:#32CD32">GeeksforGeeks</h1>
         <form>
            Name : <input class="gfg" type="text" id="name"/> 
            <br> 
            <br>
            Email : <input class="gfg" type="text" id="email" />
         </form>
         <br>
         <iframe class="gfgiframe" id="gfgiframe" src="Provide the path of your iframe webpage">
         </iframe>
         <br>
         <br>
         Contact : <input class="gfg" type="text" id="contact" /> 
         <br> 
         <br>
         <input type="button" value="Submit" id="submit" style="width:100px;background-color:#gray"/>
      </center>
   </body>
</html>


For the iframe, we used another webpage and provided its URL in src. The HTML codes of the iframe are given below.

HTML
<!DOCTYPE html>
<html>
   <head></head>
   <body>
      <center>
         <br> 
         <br>
         <form>
            <textarea type="text" rows="8" style="width:350px" id="Textmessage" placeholder="Message">
            </textarea> 
         </form>
      </center>
   </body>
</html>


Webpage Output:

gfg111
Layout of Webpage


Here we have to submit some of the information on the Geeksforgeeks page.

  • Name
  • Email
  • Message
  • Contact No.

Now let’s see the script for automating the webpage and to fill in the information by using Java.

Program 1: To handle the web element of a single iframe ( switching the focus of selenium by using an index )

To switch the focus of selenium from the main page to the iframe, here we are going to use the index method.

Syntax:

driver.switchTo().frame(index number);

It’s a first iframe and we know that index count starts with zero. So we will give the index number as zero(0). To switch back to the main frame we will use driver.switchTo().parentFrame(); method 

Java
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class GFG_Iframe {

    public static void main(String[] args) 
    {
        // Using chrome as a browser
        System.setProperty("webdriver.chrome.driver"," Path of Chromedriver.exe");
        
        // Webdriver object
        WebDriver driver = new ChromeDriver();
        
        // We have created one webpage by using html
        driver.get("Provide your webpage link");
        
        // To maximize the page
        driver.manage().window().maximize();
        
        // To delete all the cookies
        driver.manage().deleteAllCookies();
        
        // Providing implicit wait 
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
        
        //Enter name by id
        driver.findElement(By.id("name")).sendKeys("Suraj Bade");
        
        
        // Enter E-mail with xpath
        driver.findElement(By.xpath("//input[@id='email']")).sendKeys("badesuraj9@gmail.com");
       
        // Switching the focus of selenium from main page to iframe 
        // we are using index here 
        driver.switchTo().frame(0);
        
        // Enter a message text 
        driver.findElement(By.xpath("//textarea[@id='Textmessage']")).sendKeys("Thank you for creating such a knowledgeable platform. ");
        
        // Switching the focus of selenium from iframe to main page 
        driver.switchTo().parentFrame();
        
        // to enter the contact number 
        driver.findElement(By.xpath("//input[@id='contact']")).sendKeys("0102030405");
        
        // Enter contact with xpath
        driver.findElement(By.xpath("//input[@id='submit']")).click();
        
        // to close the tab
        driver.quit();
    }
}


Output:


Program 2: To handle the web element of a single iframe ( switching the focus of selenium by using id or name )

To switch the focus of selenium from the main page to the iframe, here we are going to use the id/name method.

Syntax:

driver.switchTo().frame(“value”);

In HTML codes we can check the id value/name value. here id value is given as gfgiframe. we will use this value in our method. To switch back to the main frame we will use driver.switchTo().parentFrame(); method

Java
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class GFG_Iframe {

    public static void main(String[] args) 
    {
        // Using chrome as a browser
        System.setProperty("webdriver.chrome.driver"," Path of Chromedriver.exe");
        
        // Webdriver object
        WebDriver driver = new ChromeDriver();
        
        // We have created one webpage by using html
        driver.get("Provide your webpage link");
        
        // To maximize the page
        driver.manage().window().maximize();
        
        // To delete all the cookies
        driver.manage().deleteAllCookies();
        
        // Providing implicit wait 
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
        
        // Enter name by id
        driver.findElement(By.id("name")).sendKeys("Suraj Bade");
        
        // Enter E-mail with xpath
        driver.findElement(By.xpath("//input[@id='email']")).sendKeys("badesuraj9@gmail.com");
       
        // Switching the focus of selenium from main page to iframe 
        // we are using id value here 
        driver.switchTo().frame("gfgiframe");
        
        // Enter a message text 
        driver.findElement(By.xpath("//textarea[@id='Textmessage']")).sendKeys("Thank you for creating such a knowledgeable platform. ");
        
        // Switching the focus of selenium from iframe to main page 
        driver.switchTo().parentFrame();
        
        // to enter the contact number 
        driver.findElement(By.xpath("//input[@id='contact']")).sendKeys("0102030405");
        
        // Enter contact with xpath
        driver.findElement(By.xpath("//input[@id='submit']")).click();
        
        // to close the tab
        driver.quit();
    }

}


Output:


Program 3: To handle the web element of a single iframe ( switching the focus of selenium by using webelement )

To switch the focus of selenium from the main page to the iframe, here we are going to use webElement method.

Syntax:

driver.switchTo().frame(webElement);

Here first we declare a webElement by using the attributes of iframe and then we will pass that webelement in above method. To switch back to main frame we will use driver.switchTo().parentFrame(); method

Java
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class GFG_Iframe {

    public static void main(String[] args)
    {
        // Using chrome as a browser
        System.setProperty("webdriver.chrome.driver","Path of chromedriver.exe");
        
        // Webdriver object
        WebDriver driver = new ChromeDriver();
        
        // We have created one webpage by using html
        driver.get("provide your webpage link");
        
        // To maximize the page
        driver.manage().window().maximize();
        
        // To delete all the cookies
        driver.manage().deleteAllCookies();
        
        // Providing implicit wait 
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
        
        //Enter name by id
        driver.findElement(By.id("name")).sendKeys("Suraj Bade");
        
        // Enter E-mail with xpath
        driver.findElement(By.xpath("//input[@id='email']")).sendKeys("badesuraj9@gmail.com");
        
        // declaring a webelement from the attributes of iframe 
        WebElement gfg = driver.findElement(By.xpath("//iframe[@id='gfgiframe']"));
        
        //Switching the focus of selenium from main page to iframe 
        driver.switchTo().frame(gfg);
        
        // Enter a message text 
        driver.findElement(By.xpath("//textarea[@id='Textmessage']")).sendKeys("Thank you for creating such a knowledgeable platform. ");
        
        // Switching the focus of selenium from iframe to main page 
        driver.switchTo().parentFrame();
        
        // to enter the contact number 
        driver.findElement(By.xpath("//input[@id='contact']")).sendKeys("0102030405");
        
        // Enter contact with xpath
        driver.findElement(By.xpath("//input[@id='submit']")).click();
        
        // to close the tab
        driver.quit();
    }

}


Output:


How to handle nested iframe in selenium webDriver

We will use HTML codes for designing the nested iframe

HTML codes for the main page: 

HTML
<!DOCTYPE html>
<html>
   <head>
      <style>
         .gfg 
         {width:200px}
      </style>
   </head>
   <body>
      <center>
         <h1 style="color:#32CD32">GeeksforGeeks</h1>
         Statement 1 : <input class="gfg" type="text" id="Statement1"/> 
         <br>
         <br>
         <iframe class="gfgiframe" id="gfgiframe"  width="600" height="300" src="Provide the path of iframe1 webpage">
         </iframe>
         <br> 
         <br>
         Statement 4 : <input class="gfg" type="text" id="Statement4" /> 
         <br> 
         <br>
      </center>
   </body>
</html>


HTML codes for the iframe1:

HTML
<!DOCTYPE html>
<html>
   <head>
      <style>
         .gfg 
         {width:200px}
      </style>
   </head>
   <body>
      <center>
         <h2 style="color:Black">Iframe 1 </h2>
         Statement 2 : <input class="gfg" type="text" id="Statement2"/> 
         <br>
         <br>
         <iframe class="gfgiframe2" id="gfgiframe2" width="500" height="120"src="Provide the path of iframe2 webpage">
         </iframe>
      </center>
   </body>
</html>


HTML codes for the iframe2:

HTML
<!DOCTYPE html>
<html>
   <head>
      <style>
         .gfg 
         {width:200px}
      </style>
   </head>
   <body>
      <center>
         <h2 style="color:Black">Iframe 2 </h2>
         Statement 3 : <input class="gfg" type="text" id="Statement3"/> 
         <br>
         <br>
      </center>
   </body>
</html>


Webpage Output:

NiframeTitle1
Layout of Webpage


Here we can observe,

  • Statement 1 and Statement 4 are located on main page. 
  • Statement 2 located on iframe 1 and Statement 3 is located on iframe 2. 
  • iframe 1 is located inside iframe 2.


Program 3: To handle the web element of nested iframe

Java
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class GFGNestedIframe {
    
    public static void main(String[] args)
    {
        // we are using chrome driver
        System.setProperty("webdriver.chrome.driver","Path of chromedriver.exe");
        
        // Webdriver object 
        WebDriver driver = new ChromeDriver();
        
        // etering the URL 
        driver.get("Provide your webpage link");
        
        // to maximize the window 
        driver.manage().window().maximize();
        
        // to delete all cookies
        driver.manage().deleteAllCookies();
        
        // Providing implicit wait 
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
              
        //Giving text input in Statement1
        driver.findElement(By.xpath("//input[@id='Statement1']")).sendKeys("My Statement 1");
        
        // Switching the focus of selenium from main page to iframe1
        driver.switchTo().frame(0);
        
        // Giving text input in Statement2
        driver.findElement(By.xpath("//input[@id='Statement2']")).sendKeys("My Statement 2");
        
        // Switching the focus of selenium from iframe1 to iframe2
        driver.switchTo().frame(0);
                
        // Giving text input in Statement3
        driver.findElement(By.xpath("//input[@id='Statement3']")).sendKeys("My Statement 3");
        
        // Switching the focus of selenium from iframe2 to main page 
        driver.switchTo().defaultContent();
                      
        // Giving text input in Statement4
        driver.findElement(By.xpath("//input[@id='Statement4']")).sendKeys("My Statement 4");
                
    }

}


Output:


Explanation:

We can directly identify Statement 1 as it is located on the main page but for Statement 2 we need to switch the focus of selenium from the main page to iframe 1. So we will use driver.switchTo().frame(); method with index zero. Now the focus of selenium is on iframe 1 so we can directly identify Statement 2 but for Statement 3 we again need to switch the focus of selenium from iframe 1 to iframe 2. So we will again use driver.switchTo().frame(); method with index zero, Now the focus of selenium is on iframe 2 so we can directly identify Statement 3. For locating the Statement 4 we need to switch the focus of selenium from iframe 2 to main page, so here we will use the driver.switchTo().defaultContent(); method.
 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads