24. Handling iFrames using Selenium Webdriver

In this tutorial we will learn handling iFrames using Selenium Webdriver. iFrame is a HTML document embedded inside an HTML document. iFrame is defined by an <iframe></iframe> tag in HTML. With this tag you can identify an iFrame while inspecting the HTML tree.
Here is an sample HTML code of a HTML page which contains two iFrames.

You can find iFrame’s test page here http://toolsqa.com/iframe-practice-page/. We will use this to learn iFrame handling logic. Before starting we have to understand that to work with different iFrames on a page we have to switch between these iFrames. To Switch between iFrames we have to use the driver’s switchTo().frame command. We can use the switchTo().frame() in three ways:
·         switchTo.frame(int frameNumber)Pass the frame index and driver will switch to that frame.
·         switchTo.frame(string frameNameOrId)Pass the frame element Name or ID and driver will switch to that frame.
·         switchTo.frame(WebElement frameElement)Pass the frame web element and driver will switch to that frame.
Here is the image showing all the three overloads:
How to find total number of iFrames on a webpage
There are two ways to find total number of iFrames in a web page. First by executing a JavaScript and second is by finding total number of web elements with a tag name of iFrame. Here is the code using both these methods:

package Others;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class dropdown {
    public WebDriver driver;
    @Test
    public void testSelectBirthMonth() {       
                 
            // By finding java script executor
            JavascriptExecutor exe = (JavascriptExecutor) driver;
                        Integer numberOfFrames = Integer.parseInt(exe.executeScript("return window.length").toString());
                        System.out.println("Number of iframes on the page are " + numberOfFrames);

                        //By finding all the web elements using iframe tag
                        List<WebElement> iframeElements = driver.findElements(By.tagName("iframe"));
                        System.out.println("The total number of iframes are " + iframeElements.size());
                          
    }
    @BeforeClass
    public void beforeClass() throws Exception {
            System.setProperty("webdriver.chrome.driver", "D:\\Softwares\\chromedriver_win32\\chromedriver.exe");   
                        driver = new ChromeDriver();
                        driver.get("http://toolsqa.com/iframe-practice-page/");      
    }
    @AfterClass
    public void afterClass() {
        driver.quit();
    }
}

Switch to Frames by Index

Index of an iFrame is the position at which it occurs in the HTML page. In the above example we have found total number of iFrames. In the sample page we have two IFrames, index of iFrame starts from 0. So there are two iFrames on the page with index 0 and 1. Index 0 will be the iFrame which exists earlier in the HTML page. Refer to the image below: 


to switch to 0th iframe we can simple write driver.switchTo().frame(0). Here is the sample code:


public static void main(String[] args) throws InterruptedException {
                        WebDriver driver = new FirefoxDriver();
                        driver.get("http://toolsqa.com/iframe-practice-page/");

                        //Switch by Index
                        driver.switchTo().frame(0);
                        driver.quit();
            }

Switch to Frames by Name

Now if you take a look at the HTMLcode of iFrame you will find that it has Name attribute. Name attribute has a value iframe1. We can switch to the iFrame using the name by using the commanddriver.switchTo().frame(“iframe1?).

 Here is the sample code:

            WebDriver driver = new FirefoxDriver();
            driver.get("http://toolsqa.com/iframe-practice-page/");

            //Switch by frame name
            driver.switchTo().frame("iframe1");
            driver.quit();

Switch to Frame by ID

Similar to the name attribute in the iFrame tag we also have the ID attribute. We can use that also to switch to the frame. All we have to do is pass the id to the switchTo command like thisdriver.SwitchTo().frame(“IF1?)

Here is the sample code: 

            WebDriver driver = new FirefoxDriver();
            driver.get("http://toolsqa.com/iframe-practice-page/");

            //Switch by frame ID
            driver.switchTo().frame("IF1");
            driver.quit();


Switch to Frame by WebElement

Now we can switch to an iFrame by simply passing the iFrame WebElement to thedriver.switchTo().frame() command. First find the iFrame element using any of the locator strategies and then passing it to switchTo command.

Here is the sample code:

            WebDriver driver = new FirefoxDriver();
            driver.get("http://toolsqa.com/iframe-practice-page/");
            //First find the element using any of locator stratedgy
            WebElement iframeElement = driver.findElement(By.id("IF1"));

            //now use the switch command
            driver.switchTo().frame(iframeElement);
            driver.quit();

Switching back to Main page from Frame

There is one very important command that will help us to get back to the main page. Main page is the page in which two iFrames are embedded. Once you are done with all the task in a particular iFrame you can switch back to the main page using the switchTo().defaultContent().

Here is the sample code which switches the driver back to main page.

            WebDriver driver = new FirefoxDriver();
            driver.get("http://toolsqa.com/iframe-practice-page/");
            //First find the element using any of locator stratedgy
            WebElement iframeElement = driver.findElement(By.id("IF1"));

            //now use the switch command
            driver.switchTo().frame(0);

            //Do all the required tasks in the frame 0
            //Switch back to the main window
            driver.switchTo().defaultContent();

            driver.quit();

2 comments:

  1. Can you explain how to handle nested frame ... means a frame inside a frame and then you have your elemeny

    ReplyDelete
    Replies
    1. First you find the index of main frame
      driver.switchTo.frame(mainFrameindex);
      Then find the index of sub frame in the main frame
      driver.switchTo.frame(subFrameIndex);
      You cannot directly switch to a child frame without first switching to the parent frame. This is how it works.

      Delete