All IT Courses 50% Off
Selenium Tutorials

Handling iFrames in Selenium Webdriver

switchTo() Method

In this article, we will learn about handling iFrames in Selenium the iFrame is a web page or an HTML document that is embedded in another web page or embedded inside another HTML document.

iFrames are commonly used to display advertisements from another source into a Web page. iFrames are mentioned explicitly on HTML document using the HTML tag <iframe>.

Identification of iframe:

We cannot identify the frames just by seeing the page or by inspecting the element.

In the below image, Advertisement being displayed is an iFrame, we cannot locate or identify just by inspecting it. So the question arises how can we identify the iFrame?

We can identify the iFrames using the below methods:

All IT Courses 50% Off
  1. If you find an option like ‘This Frame’ when you right-click on the element, then it is a frame.
  2. Right-click on the web page and click on ‘View Page Source’ and search with the word ‘iframe’, if you find any tag name with the ‘iframe’ then we can say the page consists an iframe.

We use below automation test if we want to find any web page has any frames by performing a search using the tag iframe

tagname.png

Methods in Selenium for handling iFrames

Selenium provides the following built-in methods to switch back and forth from iFrames.

  • switchTo.frame(string frameName)
  • switchTo.frame(int frameNumber)
  • switchTo.frame(WebElement frameElement)
  • switchTo().defaultContent()

1: switchTo.frame(int frameNumber)

  • By using the frame id this method allows users to switch to a particular frame.
  • The frame number initially starts with zero-based index value which means the first frame of the web page has value with index 0, the second frame has index value 1, and the third frame has index 3 and so on.
  • Using Frame ID of the element we can identify the frame number. It is done by Right-click > Inspect element and search for the iFrame. Validate if any of the Handling iFrames have an attribute ID.

Source code of a sample iframe element will look like

<iframe id =”a009aa” name =”a009aa” src=”abc.html” scrolling=”no” width=”750px;” height=”120px;”></iframe>

Once the iFrame id is identified, we can use it to switch to the frame.

Examples:

driver.switchTo.frame(“a009aa”);
driver.switchTo.frame(0);

The above method will throw NoSuchFrameException when the required frame is not found on the current web page.

2: switchTo.frame(string frameName)

  • By using with developer-defined name of the frame this method will allow users to switch to a particular frame.
  • The frame needs to be enclosed within double quotes to consider it as a String parameter.
  • The above method will throw NoSuchFrameException when the required frame is not found on the current web page.

Example:

In the above code, both the frame ID and frame name have the same value. SwitchTo frame can be accomplished using the frame name

driver.switchTo.frame(“a009aa”);

3: switchTo.frame(WebElement frameElement)

  • This method will allow users to switch to a frame based on the location of the Web Element.
  • The above method will throw NoSuchFrameException when the required frame is not found on the current web page and StaleElementReferenceException if the frame displayed on the web page is not active.

Example:

WebElement frameElement = driver.findElement(By.id(“a009aaaa”));
driver.switchTo.frame(frameElement);

4: switchTo().defaultContent()

  • Using the method driver.switchTo.defaultContent() we can switch back and forth between iframes and parent page.
  • In Selenium we have a method driver.SwitchTo().parentFrame() to switch between frames
  • The difference between driver.switchTo().defaultContent() and driver.switchTo().parentFrame() is that the first method switches the control to the main web page regardless of the number of frames within the web page, while the second method switches the control to the parent frame of the current frame.

Sample Source code:

Consider the below test scenario to be automated using iframes in selenium:

  • Open the dezlearn.com/testingpage/ website.
  • Find all the HTML elements with the tag iframe, count the number of occurrences of the iFrame, and print it on a console.
  • Switch to a valid frame on the web page using the frame id and print the source code of the frame.
  • Close the current browser window.
package basic.tests;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FramesHandling {

public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver","F:\\drivers\\geckodriver.exe");  
     WebDriver driver = new FirefoxDriver();
     driver.get("dezlearn.com/testingpage/");

    
//Finding all iframe tags on a web page  
List<WebElement> elements = driver.findElements(By.tagName("iframe"));
     int numberOfTags = elements.size();
     System.out.println("No. of Iframes of the Web Page: " +numberOfTags);
      
// Switch to the frame using the frame id
     driver.switchTo().frame("contact-iframe");
    

// Switch back to main web page
driver.switchTo().defaultContent();

   
     driver.quit();

}

}

Code Output:

Open the website: dezlearn.com/testingpage/

dezinia.PNG

Switch to the frame named contact-iframe.

Print the number of iframes on the web page on the console.

noframes.PNG

Code Explanation:

  • Using the System.setProperty method we are initializing an object of gecko driver and point to the geckodriver.exe file path.
  • Through the WebDriver interface, we are instantiating an object of Firefox driver.
  • Using the firefox driver object, the following webpage: dezlearn.com/testingpage/ is opened.
  • Next, we are identifying the number of iframe elements on the web page, counting them, and displaying the iframe count.
  • We are switching to the frame on the web page using the frame id. In the above case, the frame id is ‘contact-iframe’.
  • Using driver.switchTo().defaultContent() statement we are then switching back to the parent web page.
  • Finally, we close the web driver instance using the driver.quit method.

Handling Dynamic Frames in Selenium

  • In some web pages, properties such as frame id and frame name can dynamically change on a web page. However, the position of the frame will remain the same. In such cases, we can’t depend on frame id or frame name to identify a frame uniquely.
  • In such cases, we use the frame index to uniquely identify the frame based on the frame position.
  • In some cases, when the page loads the frame id value changes every time, but with a static text that does not change. For example, consider the below code

<iframe id =’frame_12345’>...</iframe>

In the above example, the text ‘frame_’ will remains constant while the numeric value changes each time the page load.

  • We can identify the above frame uniquely using below code

//iframe[contains(@id,’frame’)]

How to Locate the elements inside the Frame

To access the elements that are present inside the frame, first, we need to switch inside the frame and we identify the elements as we normally do use selenium locators. Without switching into the frame we cannot locate your elements.

Multiple Ways to Switch to an IFrame using Selenium

1: Using Frame name or id

Switching to IFrame using Frame id or Frame name, sometimes either Frame id or Frame name or sometimes both will be present in code.

Syntax:

driver.switchTo().frame(1); //for id driver.switchTo().frame(“abcd”); //for name

2: Using Frame Index

Locate the frame by using the frame index.

Syntax:

driver.switchTo().frame(0); // frame index starts with 0

3: Using Web Element

Locate the frame by using Selenium locators.

Syntax:

driver.switchTo().frame("Locate the frame using any other locator");

Other Operations Using Frames

1: Switching Back to the Parent Frame

If you want to switch back from frame 4 to frame 3 we use the “switchTo.parentFrame” command.

Syntax:

driver.switchTo().parentFrame();

2: Switching to any other Frame

If you want to switch from frame 4 to frame 1 or the default frame, then use “switchTo.defaultContent” command.

Syntax:

driver.switchTo().defaultContent();

In the below code we are locating a name text box present inside a frame.

What will happen if we try to locate it directly without switching into the frame?

Let’s see the result:  

Code failed with reason “Unable to locate element: {“method”:”xpath”,”selector”:”//input[@name='name']”}

package basic.tests;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FramesExample {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver","F:\\drivers\\geckodriver.exe");  
     WebDriver driver = new FirefoxDriver();
        driver.get("https://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_submit");
        driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("Testing");
        driver.close();
}

}

The following error will display in the console when you run the above program

unabletolocate.PNG

Now switch inside the frame using Web Element or by using Selenium locator and locate the text box field.

Given below is the Complete Code for Switching inside the Frame: 

package basic.tests;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FramesExample {

public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver","F:\\drivers\\geckodriver.exe");  
     WebDriver driver = new FirefoxDriver();
        driver.get("https://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_submit");
        
        driver.switchTo().frame("iframeResult");
        
        driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("Mark");
        
        driver.switchTo().parentFrame();
        
        Thread.sleep(5000);
        driver.close();
}

}

Output:

john.PNG

This is how we switch between the frames for locating the elements using Selenium.

Conclusion

  • iFrame is a web page or an HTML document that is embedded in another web page or embedded inside another HTML document.
  • To allow the users to switch to a particular frame using the frame id we use the method switchTo.frame(int frameNumber).
  • To allow the users to switch to a particular frame using the developer-defined name we use the method frame.switchTo.frame(string frameName).
  • To allow the users to switch to a frame based on the location of the Web Element we use the switchTo.frame(WebElement frameElement) method.
Facebook Comments

Related Articles

Back to top button