What is Iframe in Selenium?


An Iframe stands for Inline Frame, is a web page that is embedded inside another web page or an HTML document embedded inside another HTML document on a web page. HTML provides the flexibility to embed external documents or documents from another website by using the <iframe> tag. 

For example, various social media widgets such as facebook, twitter, WhatsUp, and website can be easily embedded in the web application by using <iframe> tag. An example of the Facebook Like link embedded on a web page is shown in the below screenshot.
Embedded iframe on a web page in selenium using <iframe> tag
A single web page can have any number of iframes (inline frames) to represent a new web page inside the main page of a website. They can be either multiple iframes or nested iframes. The iframes are defined by an iframe tag such as <iframe>...<iframe> in HTML.

It is very easy to handle inline frames if a user finds out all the frames available in a web page. The developer debugging tool of google chrome can be used to check the availability of iframes.

How to identify an Iframe on a Webpage?


You cannot detect the frame by just seeing the page. There are two ways to detect iframe on any web page. They are as follows:
1. Right click on the element and see an option like 'This Frame'. If you find, it is an iframe. An example is shown in the below screenshot.
Ways to identify Iframe on Webpage in Selenium
2. Right-click on the web page, click on the option 'View Page Source' and press ctrl+F. Now you will see "search" option on top bar. You can search by writing 'iframe' in it. If you find any tag name with the 'iframe', it represents that the page consisting an iframe.

Syntax for Frame in WebDriver


There are three versions of syntax available in Webdriver for the frame. They are as follows:
Syntax:
1. WebDriver frame( int index )
This method accepts an input parameter as an index of frame that we want to switch to. If a web page contains four frames, WebDriver index them as 0, 1, 2, 3, and 4, where zero index is assigned to the first frame in the DOM.

2. WebDriver frame( String frameName or frameID )
This is the overloaded method of previous. It accepts the name of frame or its ID as an input parameter. This method helps to switch to the frame if you are not sure about index of the target frame.

3. WebDriver frame( WebElement frameElement )
This is another overloaded version of the method. It takes an input parameter as WebElement of the frame. 

Syntax to handle IFrames in Selenium


To handle iframes, it is important to know you how to switch into iframe and how to move back from an iframe to the main frame. The syntax for switching iframes is as follows:
Syntax:
      driver.switchTo().frame();

Brief Introduction on switchTo () Method

Selenium WebDriver provides a switchTo() method which is mainly used to switch between multiple child windows, browser tabs, and frames in the web application. This command is called using driver object. The syntax for switchTo() method is as follows:
Syntax:
        WebDriver TargetLocator switchTo()

The return type of switchTo() method is TargetLocator. The syntax to call switchTo() method of WebDriver interface is given below:
Syntax:
          driver.switchTo();

How to switch over elements in iframe using WebDriver commands?


Selenium WebDriver provides three ways to switch over the elements in an iframe.
  • By Index
  • By Name or Id
  • By Web Element

Switching to the frame by index:

An index is an attribute for the Iframe through which we can switch to it. Index value of the iframe starts with '0' and goes on to 0,1, 2... For example, suppose that there are 100 frames on the webpage, you can switch to iframe by using index value.
    driver.switchTo().frame(0);
    driver.switchTo().frame(1);
    driver.swicthTo().frame(2);

Let's take a scenario where we will identify all the frames by their index value. We will also handle switching between the frames of a web page. So, let's see at a glance on the following scenarios.
Scenarios to Automate:
1. Launch the Firefox web browser.
2. Maximize web browser.
2. Open the main web page URL https://selenium08.blogspot.com/2019/11/selenium-iframe.html.

3. Wait for some time to load the page completely.
4. Locate the total number of frames on the main web page.
5. Locate and switch driver context to the first iframe by its index value.
6. After switching, locate the web element search box on the frame by By.xpath, send a text "Selenium Jobs" and then click on the search button.

7. Now, switch from the first frame to the main web page.
8. Get the title and current URL of the main web page.
9. Again switch driver context to the second frame by its index value.
10. Locate the web element "Register with us" on the second frame and click it. At last, quite all web pages on open web browser.

Now, it's time to write WebDriver code to automate the above following scenarios.
Program source code 1:
    package seleniumProject; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class FrameDemo { public static void main(String[] args) { // Create a driver object for Firefox browser. WebDriver driver= new FirefoxDriver(); // Maximize the web browser. driver.manage().window().maximize(); // Store the URL in a variable of type String. String URL = "https://selenium08.blogspot.com/2019/11/selenium-iframe.html"; // Call get() method and pass the URL as a parameter. driver.get(URL); // Wait for some time to load web page completely. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Locate the total number of iframes on the web page. int iFrameSize = driver.findElements(By.tagName("iframe")).size(); System.out.println("Toal no of iframes: " +iFrameSize); // Locate the first iframe and switch driver to first iframe by index value 0. driver.switchTo().frame(0); driver.findElement(By.xpath("//input[@itemprop = 'query-input']")).sendKeys("Selenium Jobs"); driver.findElement(By.xpath("//button[@class = 'wpb_button wpb_btn-inverse btn']")).click(); // Now, switch to main web page from iframe by using defaultContent() method. driver.switchTo().defaultContent(); // Closing first frame. String getTitleOfMain = driver.getTitle(); System.out.println("Title of main web page: " +getTitleOfMain); String mainPageURL = driver.getCurrentUrl(); System.out.println("URL of main web page: " +mainPageURL); // Switch to second iframe by its index value 1. driver.switchTo().frame(1); driver.findElement(By.xpath("//input[@value = 'Register with us']")).click(); driver.quit(); } }
    Output: Total no of iframes: 4 Title of main web page: Selenium IFrame URL of main web page: https://selenium08.blogspot.com/2019/11/selenium-iframe.html
Explanations:
1. In the preceding code, there are four frames. First is Freshersnow.com, second is naukri.com, third is Facebook Like and Share link, and the fourth is comment-form. In order to handle all these frames, the first you need to locate frame by ID or name and then switch driver context to this frame.

2. The statement driver.switchTo().frame(); is used to move across frames.
3. The statement driver.switchTo().defaultContent();  is used to get back to the main web page (that contains frames). It helps to switch driver context back to the parent frame or window.

4. To switch from one frame to another frame directly is not allowed. It is essential to close the current frame. Closing an iframe means moving from the current frame to the main web page. Only switching from main window or frame to another frame and vice-versa are allowed. 

If you switch from the first frame to second frame directly, you will get an exception "NoSuchFrameException". After switching to main web page, you can now switch to the second frame easily by using the following code: driver.switchTo().defaultContent();. Thus, we can switch between the frames and execute the corresponding WebDriver actions.

Switching to the Frame by name or id Attribute


Attribute name or id of the frame can be used to locate a frame on a web page. The syntax for switching to the frame on a web page is as follows:
Syntax:
         driver.switchTo().frame( String frameName or frameID );
For example:
         driver.switchTo().frame("frame_a");

Let's write WebDriver code to locate the first frame on a web page by using its name attribute. HTML code of the first frame is given below:

<iframe name="iframe_a" src="https://freshersnow.com" style="border: 6px solid red; height: 400px; width: 1000px;"></iframe>

An attribute name of the above frame is frame_a. The following code shows how to switch to the first frame using its name attribute.
Program source code 2:
    package seleniumProject; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class FrameDemo2 { public static void main(String[] args) { // Create a driver object for Firefox browser. WebDriver driver = new FirefoxDriver(); // Maximize the web browser. driver.manage().window().maximize(); // Store the URL in a variable of type String. String URL = "https://selenium08.blogspot.com/2019/11/selenium-iframe.html"; // Call get() method and pass the URL as a parameter. driver.get(URL); // Wait for some time to load web page completely. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Locate iframe and switch driver context to first iframe by value of name attribute. System.out.println("Switching to first frame from main web page"); driver.switchTo().frame("iframe_a"); driver.findElement(By.xpath("//input[@itemprop = 'query-input']")).sendKeys("Selenium Jobs"); driver.findElement(By.xpath("//button[@class = 'wpb_button wpb_btn-inverse btn']")).click(); // Switch to main web page from iframe by using defaultContent() method. System.out.println("Switching to main web page from first frame"); driver.switchTo().defaultContent(); // Click on link text. driver.findElement(By.xpath("//a[text() = 'Freshers Now']")).click(); System.out.println("Clicked on link text successfully."); driver.quit(); } }
    Output: Switching to first frame from main web page Switching to main web page from first frame Clicked on link text successfully.

Switching to Frame using WebElement


It is also possible to switch to the frame by Web Element. The syntax to switch to the frame by WebElement is as follows:
Syntax:
         driver.switchTo().frame(WebElement FrameElement);

Let's write WebDriver code to switch to the second frame (Naukri) by using WebElement. Follow all the steps to implement the above concepts.
Program source code 3:
    package seleniumProject; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class FrameDemo3 { public static void main(String[] args) { WebDriver driver= new FirefoxDriver(); driver.manage().window().maximize(); String URL= "https://selenium08.blogspot.com/2019/11/selenium-iframe.html"; driver.get(URL); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Locate second frame (Naukri) by WebElement. WebElement frameElement = driver.findElement(By.name("iframe_b")); // Here, frame is located by using name attribute. System.out.println("Switching to second frame from main web page"); driver.switchTo().frame(frameElement); // Passing frameElement as an input parameter to frame(). // After switching to the frame, locate element CREATE JOB ALERT By.xpath. WebElement jobAlert = driver.findElement(By.xpath("//a[text() = 'CREATE JOB ALERT' ]")); jobAlert.click(); // Switch to main web page from iframe by using defaultContent() method. System.out.println("Switching to main web page from second frame"); driver.switchTo().defaultContent(); driver.quit(); } }
    Output: Switching to second frame from main web page Switching to main web page from second frame
In the preceding code, we have just located the frame element first by using findElement() method and name attribute of the frame and then switch WebDriver object context to this frame element.

Final words
Hope that this tutorial has covered almost all important points related to Iframe in Selenium WebDriver. I hope that you will have understood how to work & handle iframe in Selenium and switching between two frames. 

Please, share this tutorial for your friends on social networking sites.
Thanks for reading!