Handle Frames / IFrames In Selenium WebDriver

Frame is a widely used html web element in web page design. It’s purpose is to include other web pages into current web page. There are two kind of html tags. One is <frame> which is used to add a fixed size and position one, the other is <iframe> which is used to add a floating and resizable one. But how to manipulate them in selenium webdriver automation testing scripts? Please read on.

Html Files In This Example

  1. TestFramePage.html
    <html>
    <head>
    <meta charset="UTF-8">
    <title>This is TestFramePage.html</title>
    </head>
    <frameset cols="50%,50%">
      <frame name="leftFrame" src="TestChildFramePage.html" />
      <frame id="rightFrame" src="TestIFramePage.html" />
    </frameset>
    </html>

    This page include two fixed size and position frame web element. Each one occupy fifty percent of the width. You should include them them in html frameset tag. And html body tag can not exist in the page.

  2. TestChildFramePage.html
    <html>
    <head>
    <meta charset="UTF-8">
    <title>This is TestChildFramePage.html</title>
    </head>
    <frameset rows="30%,70%">
      <frame name="upFrame" src="pageUpFrame.html" />
      <frame id="downFrame" src="pageDownFrame.html" />
    </frameset>
    </html>

    This is the first web page in TestFramePage.html. It also include two fixed frame. The upFrame include web page pageUpFrame.html which include one line text and an input button, the downFrame include web page pageDownFrame.html which only include one line text.

  3. TestIFramePage.html
    <html>
    <head>
    <meta charset="UTF-8">
    <title>This page include two iframe</title>
    </head>
    <body>
    <iframe src="pageIFrame1.html" height="300" width="600"></iframe>
    
    <iframe src="pageIFrame2.html" height="300" width="500"></iframe>
    
    </body>
    </html>

    This is the second web page in TestFramePage.html. It include two floating iframe. The first iframe include web page pageIFrame1.html, the second iframe include web page pageIFrame2.html which include a input text box and a button.

  4. When you use Firefox browser to open TestFramePage.html, it will show a web page like below.
    example web page with frame and iframe
    example html web page file list

How To Switch To The Frame/IFrame Use Selenium WebDriver

WebDriver’s switchTo() method return a TargetLocator object, this locator provide below method.

  1. Common method used in this example to verify the switch action success.
    	public static int getTotalFrameCountInCurrentPage(WebDriver driver)
    	{
    		int ret = 0;
    		
    		By byFrameTag = By.tagName("frame");
    		List<WebElement> frameList = driver.findElements(byFrameTag);
    		int frameSize = frameList.size();
    		
    		System.out.println("There are " + frameSize + " frame in current web page.");
    		
    		By byIFrameTag = By.tagName("iframe");
    		List<WebElement> iframeList = driver.findElements(byIFrameTag);
    		int iframeSize = iframeList.size();
    		
    		System.out.println("There are " + iframeSize + " iframe in current web page.");
    		
    		ret = frameSize + iframeSize;
    				
    		return ret;
    	}
  2. Switch to by index. switchTo().frame(int frameNumber)
    The frames in a web page is stored in an array started with index 0.

    	public static void getFrameByIndex(WebDriver driver, int frameIndex)
    	{
    		// Switch to by index.
    		driver.switchTo().frame(frameIndex);
    		
    		// Check whether the switch action successfully or not.
    		int totalFrameCount = TestHtmlFrame.getTotalFrameCountInCurrentPage(driver);
    		
    		System.out.println("There are totaly " + totalFrameCount + " frames exist in current frame which index is " + frameIndex);
    	}
  3. Switch to by name attribute. switchTo().frame(string frameName)

    	public static void getFrameByName(WebDriver driver, String frameName)
    	{
    		driver.switchTo().frame(frameName);
    		
    		int totalFrameCount = TestHtmlFrame.getTotalFrameCountInCurrentPage(driver);
    		
    		System.out.println("There are totaly " + totalFrameCount + " frames exist in current frame with name " + frameName);
    	}
  4. Switch to by id attribute. switchTo().frame(string frameId)
    	public static void getFrameById(WebDriver driver, String frameId)
    	{
    		driver.switchTo().frame(frameId);
    		
    		int totalFrameCount = TestHtmlFrame.getTotalFrameCountInCurrentPage(driver);
    		
    		System.out.println("There are totaly " + totalFrameCount + " frames exist in current frame with id " + frameId);
    	}
  5. Switch to by web element. switchTo.frame(WebElement frameElement)
    If the id or name is not exist or changed dynamically, you can use this method. You can get the frame web element via a lot of method, such as by xpath, by css selector etc.

    	public static void getFrameByXpath(WebDriver driver, String xpath)
    	{
    		By byXPath = By.xpath(xpath);
    		
    		// Get all web elements by xpath.
    		List<WebElement> iframeList = driver.findElements(byXPath);
    		
    		if(iframeList.size()>0)
    		{
    			// Get the first web element.
    			WebElement iframeElement1 = iframeList.get(0);
    			
    			// Switch to it.
    			driver.switchTo().frame(iframeElement1);
    			
    			int totalFrameCount = TestHtmlFrame.getTotalFrameCountInCurrentPage(driver);
    			
    			System.out.println("There are totaly " + totalFrameCount + " frames exist in current frame with xpath " + xpath);
    		}else
    		{
    			System.out.println("Do not find any web element with xpath " + xpath);
    		}
    	}
  6. Switch back to top web page. switchTo().defaultContent().
    After switch to, if you want to interact with other web elements out side current frame, you can use this method to goto the top web page.

    	/* Return back to top web page.*/
    	public static void returnToTopWebPage(WebDriver driver)
    	{ 
    		driver.switchTo().defaultContent();
    	}

Example To Get Child Frame In Parent

Now we want to get the username input text box and input text into it in pageIFrame2.html, which is located in the right down iframe. We should follow below steps.
example web page with frame and iframe

  1. Switch to the parent frame.
  2. Switch to the child iframe.
  3. Get the input text box web element.
  4. Use sendKeys(String text) method to input text in it.
	public static void getChildFrameByXPath(WebDriver driver, String parentFrameXPath, String childFrameXPath)
	{
		// First switch to parent
		TestHtmlFrame.getFrameByXpath(driver, parentFrameXPath);
		
		// Then switch to child iframe in parent.
		TestHtmlFrame.getFrameByXpath(driver, childFrameXPath);
		
		// Check current web page content to verify the switch action success.
		By byUserName = By.name("userName");
		List<WebElement> eleList = driver.findElements(byUserName);
		if(eleList.size()>0)
		{
			WebElement element = eleList.get(0);
			
			element.sendKeys("dev2qa.com");
			
			System.out.println("Find web element in current child web page, parent page xpath : " + parentFrameXPath + " , child page xpath : " + childFrameXPath);
			
			System.out.println("Found web element tage : " + element.getTagName() + " , value : " + element.getText());
		}
		
	}

Java Main And Test Method

	public static void main(String[] args) throws InterruptedException {
		
		String filePath = "file:///C:/WorkSpace/dev2qa.com/Code/src/com/dev2qa/webdriver/frame/TestFramePage.html";
		WebDriver ffDriver = new FirefoxDriver();
		
		ffDriver.get(filePath);
		
		//TestHtmlFrame.getTotalFrameCountInCurrentPage(ffDriver);
		
		TestHtmlFrame.testGetFrame(ffDriver);
		
		Thread.sleep(3000);
		ffDriver.close();	
	}	


public static void testGetFrame(WebDriver driver)
	{
		TestHtmlFrame.getFrameByIndex(driver, 0);
		TestHtmlFrame.returnToTopWebPage(driver);
		
		TestHtmlFrame.getFrameById(driver, "rightFrame");
		TestHtmlFrame.returnToTopWebPage(driver);
		
		TestHtmlFrame.getFrameByName(driver, "leftFrame");
		TestHtmlFrame.returnToTopWebPage(driver);
		
		TestHtmlFrame.getFrameByXpath(driver, "//frame[@id=\"rightFrame\"]");
		TestHtmlFrame.returnToTopWebPage(driver);
		
		TestHtmlFrame.getChildFrameByXPath(driver, "//frame[@id=\"rightFrame\"]","//iframe[@src=\"pageIFrame2.html\"]");
		TestHtmlFrame.returnToTopWebPage(driver);
	}

Download “HandleFramesIFramesExampleCode.zip” HandleFramesIFramesExampleCode.zip – Downloaded 42 times – 4 KB

(Visited 593 times, 1 visits today)
READ :   Use Selenium Grid To Run Testing Script

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.