Handling iFrames Using Selenium WebDriver switchTo() Method

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

Handling iFrames Using Selenium WebDriver: Hands-on Tutorial with Practical Examples

iFrame (inline frame) is a HTML document embedded within another HTML document.

iFrames are most commonly used for displaying advertisements within a web page. iFrames are explicitly mentioned on HTML document using the HTML tag <iframe>.

This tutorial will explain to you all about Handling iframes in Selenium along with the concerned code examples for your easy understanding.

=> Read Through The Easy Selenium Training Series.

Selenium Handling iFrames

Handling iFrames Using Selenium

An iframe within a web page can be identified in the Firefox browser if the option named ‘This frame’ is displayed on the right-click options as shown below.

iFrame1

Alternatively, we can also validate if a web page has any iframes by looking at the source code and searching for the tag <iframe> within the source code. From a test automation perspective, we can find if any web page has any iframes by performing a search using the tag iframe as shown below.

List<WebElements> iframes = driver.findElements(By.tagName(“iframe”));

Methods Provided by Selenium for Handling iFrames

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

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

#1) switchTo.frame(int frameNumber)

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

Sample iframe element on source code would look as mentioned below.

FrameSourceCode

Once the id of the iFrame is identified, we can use the same to switch to the frame as below.

Examples:

driver.switchTo.frame(“a077aa5e”);

driver.switchTo.frame(0);

  • This method throws NoSuchFrameException when the required frame is not found on the current web page.

#2) switchTo.frame(string frameName)

  • This method allows users to switch to a particular frame using the developer-defined name of the frame.
  • Frame name needs to be enclosed within double quotes for it to be considered as a String parameter.
  • This method throws NoSuchFrameException when the required frame is not found on the current web page.

Example:

In the code mentioned above, both the frame ID and frame name hold the same value. Switch to frame can be accomplished using the frame name as below:

driver.switchTo.frame(“a077aa5e”);

#3) switchTo.frame(WebElement frameElement)

  • This method allows users to switch to a frame based on the location of the Web Element.
  • This method throws NoSuchFrameException when the required frame is not present on the web page and StaleElementReferenceException if the frame displayed on the web page is not active.

Example:

WebElement frameElement = driver.findElement(By.id(“a077aa5e”));

driver.switchTo.frame(frameElement);

#4) switchTo().defaultContent()

  • Switching back and forth between iframes and parent page can be achieved using driver.switchTo().defaultContent() method.
  • Please note that there is a similar method in Selenium to switch between frames named driver.switchTo().parentFrame () method.
  • 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.

Example:

Suppose there are three frames named i1,i2 and i3 within the parent web page p1. Frames i1, i2, and i3 are dependant on each other which means one frame will be the parent of another.

Using driver.switchTo().defaultContent() method on frame i3, web driver control moves to the parent page, p1. While driver.switchTo().parentFrame() method on frame i3 switches the control back to frame i2 and so on.

Source code sample:

Below is the test scenario to be automated using iframes in selenium:

  • Open the SoftwareTestingHelp.com 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 Demo;
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 iFramesDemo {
public static void main(String[] args) throws InterruptedException {

System.setProperty("webdriver.gecko.driver","D:\\Data_Personal\\Demo \\geckodriver-v0.23.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.softwaretestinghelp.com/");

//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 on this Web Page are: " +numberOfTags);

// Switch to the frame using the frame id
System.out.println("Switching to the frame");
driver.switchTo().frame("aswift_0");

// Print the frame source code
System.out.println("Frame Source" +driver.getPageSource());

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

driver.quit();
}
}

Code Output:

Open the website: https://www.softwaretestinghelp.com

Code Output

Switch to the frame named aswift_0.

Switch to Frame

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

Code Output 3

Print the source code of frame on the eclipse console after switching to the frame.

word image 1

Code Explanation:

  • We are initializing an object of gecko driver using System.setProperty method to point to the geckodriver.exe file path on the local machine.
  • We are then instantiating an object of FireFox driver through the WebDriver interface.
  • Using the firefox driver object, the following webpage: https://www.softwaretestinghelp.com is opened.
  • In the next step, we are identifying the number of iframe elements displayed on the web page, counting them and displaying the iframe count on the eclipse console.
  • Using the frame id, we are switching to the frame on the web page. In the above case, the frame id is ‘aswift_0’.
  • Once we have made a switch to the frame successfully, we are printing the source code of the frame on the eclipse console.
  • We are then switching back to the parent web page using driver.switchTo().defaultContent() statement and finally closing the web driver instance using the driver.quit method.

Difference between Frame and iFrame in Selenium

  • A frame is used to divide a page into multiple sections, with new content on each section.
  • An iFrame is used to embed the content of the external websites into the web page, in order to avoid cross-site scripting issues.
  • An iFrame is considered to be less secure than a frame, as iFrame allows developers to embed content from the third party websites. Thus, an iframe requires a developer to trust the content which he has embedded in the iframe.
  • Most of the web applications being developed today do not use frames to divide the page, rather they use iframes to embed external content such as advertisements within the web page.

Handling Dynamic Frames in Selenium

  • In some web pages, frame properties such as frame id and frame name can change dynamically on a web page, however, the frame position will remain the same. In such a case, we can’t rely on the frame id or frame name to uniquely identify a frame.
  • We can use the frame index in such a case to uniquely identify the frame based on the frame position.
  • In some cases, frame id value changes every time when the page is loaded, but with a static text that does not change. For Example, consider the below code for iframes.

<iframe id = ‘frame_1234’>…</iframe>

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

  • We can identify the above frame uniquely using the below XPath

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


UPDATE on March 2020

How To Locate The Elements Inside The Frame

In Selenium, in order to access the elements present inside the frame, first, we need to switch inside the frame and then identify the elements as we normally do using different Selenium locators. Your Selenium code cannot locate your elements, without switching into IFrame.

The below screenshot shows how frames are embedded in an HTML code:

frames are embedded in an HTML

Different Ways To Switch To An IFrame Using Selenium

to switch to an IFrame

#1) Using Frame name or id

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

Syntax:

driver.switchTo().frame(1); // for id
driver.switchTo().frame("main"); // for name

#2) Using Frame Index

Locate the frame using the frame index if available.

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 xpath or by any other locator");

Other Operations Using Frame

#1) Switching Back To The Parent or Ancestor Frame

Switching back from frame 3 to frame 2 using the “switchTo.parentFrame” command.

Syntax:

driver.switchTo().parentFrame();

#2) Switching To Any Other Frame

If you want to switch from frame 3 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 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’]”}

a name text box present inside a frame.

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

switch inside the frame

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

package com.wordpress.pages;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Frame {

static WebDriver driver;

@Test
public void Test(){
System.setProperty("webdriver.chrome.driver", "D:\\Srinivas\\New folder\\exe\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://www.dwuser.com/education/content/the-magical-iframe-tag-an-introduction/");
//identifying the frame using locator or say using webelement
driver.switchTo().frame(driver.findElement(By.xpath("//div[@id='eduFooterWrap']//iframe[1]")));
driver.findElement(By.xpath("//input[@name='name']")).sendKeys("SoftwareTestingHelp.com");
} 
}

Output:

output output

This is how we need to switch between the frames for locating the elements using Selenium. If there are multiple frames on your web page then you need to switch multiple times.

Conclusion

  • iFrame is a HTML document embedded within another HTML document. iFrames are explicitly mentioned on the HTML document using the HTML tag <iframe>.
  • switchTo.frame(int frameNumber) method allows the users to switch to a particular frame using the frame id.
  • switchTo.frame(string frameName) method allows the users to switch to a particular frame using the developer-defined name of the frame.
  • switchTo.frame(WebElement frameElement) method allows the users to switch to a frame based on the location of the Web Element.

=> Check ALL Selenium Tutorials Here.

Was this helpful?

Thanks for your feedback!

Leave a Comment