Understanding how to handle iframes in Selenium is essential for testing modern web applications, as many websites embed content using frames and iframes.
Overview
What are iFrames?
iFrames (inline frames) are HTML elements that embed another HTML document within the current page.
Why handle iFrames in Selenium?
- Some critical UI components (forms, ads, widgets) are loaded inside iFrames
- Selenium cannot directly access elements within an iFrame without switching context
- Avoids common test failures like NoSuchElementException
How to handle iFrames in Selenium (syntax)
driver.switchTo().frame("frameNameOrID");
This article explains what iframes are and explores different methods to interact with them using Selenium WebDriver. It also covers how to use the SwitchTo() method to switch between frames, supported by clear code examples.
What are iframes in Selenium?
An iframe is also known as an inline frame. It is a tag used in HTML5 to embed an HTML document within a parent HTML document. An iframe tag is defined using <iframe></iframe> tags.
When testing with Selenium, you can’t directly interact with elements inside an iframe unless you first switch the WebDriver’s focus to that iframe. By default, Selenium only works with elements in the main document.
Example: If a button is inside a chatbot iframe, Selenium won’t detect it until the focus is switched to that iframe.
Properly handling iframes is essential for reliable testing, especially on modern websites with embedded content.
Difference between frame and iframe in Selenium
Frame allows splitting the browser window into sections using the <frameset> tag, typically for layout purposes.
iFrame is Used to embed external content (like ads or videos) within a page. It can be positioned freely and floats within the main page layout.
Below is a table summarizing the key comparison between frame and iframe in Selenium:
Aspect | Frame | iFrame (Inline Frame) |
---|---|---|
Definition | Divides a webpage into multiple sections, each loading its own document. | Embeds another HTML document within the current page. |
Usage in Selenium | Requires switching context to interact with elements inside the frame. | Also requires switching context before accessing elements within the iframe. |
HTML Relevance | Considered outdated in modern HTML standards. | Widely used today for embedding external or interactive content. |
Typical Use Cases | Legacy websites with split screen layouts. | Embedded videos, maps, widgets (like chatbots or login forms). |
Tag Used | <frame> | <iframe> |
Support | Limited in HTML5 and mostly deprecated. | Fully supported in HTML5 and across modern browsers. |
Note: Frame and frameset tags are deprecated as they are no longer supported by HTML 5.
Here is code snippet portrays an HTML page containing two iframes –
Code Snippet in Raw Format is below –
<html> <body> <div class="box"> <iframe name="iframe1" id="IF1" height="50%" width="50%" src="https://www.browserstack.com"> </iframe> </div> <div class="box"> <iframe name="iframe2" id="IF2" height="50%" width="50%" align="left" src="https://www.browserstack.com/"></iframe> </div> </body> </html>
How to identify a Frame on a Page?
For a browser to automatically start interacting with the web page, the browser needs to identify the elements under the frame for Selenium testing. It is possible to identify the iframes on a web page in two ways:
- Right-click on the specific element and check all the options. If you find an option like This Frame, view Frame source or Reload Frame, the page includes frames. Consider the image below as an example.
- Similar to the first step, right-click on the page and click on View Page Source.
- On the page source, search for iframe-tags. If you find any iframe tags, it means the page includes iframes.
Also Read: Quick XPath Locators Cheat Sheet
Using the SwitchTo().frame function
For a browser to work with several elements in iframes, the browser must identify all the iframes. For this purpose, we need to use the SwitchTo().frame method. This method enables the browser to switch between multiple frames. It can be implemented in the following ways:
- switchTo.frame(int frame number): Defining the frame index number, the Driver will switch to that specific frame
- switchTo.frame(string frameNameOrId): Defining the frame element or Id, the Driver will switch to that specific frame
- switchTo.frame(WebElement frameElement): Defining the frame web element, the Driver will switch to that specific frame
The image below gives a glimpse of all the commands –
Before understanding the implementation of the methods above, let’s understand how to identify the total number of frames in a web page.
There are two ways to do this:
- Executing JavaScript
- Finding the total number of elements that have the tag “iframe”
Example to find the number of frames:
WebDriver driver = new ChromeDriver(); driver.get("https:// url containing i-frames/"); //By finding all the web elements using iframe tag List<WebElement> iframeElements = driver.findElements(By.tagName("iframeResult")); System.out.println("Total number of iframes are " + iframeElements.size()); //By executing a java script JavascriptExecutor exe = (JavascriptExecutor) driver; Integer noOfFrames = Integer.parseInt(exe.executeScript("return window.length").toString()); System.out.println("No. of iframes on the page are " + numberOfFrames);
Try Handling Frames in Selenium for Free
Switching Frames in Selenium using Index
An Index number represents the position of a specific iframe on an HTML page.
Suppose if there are 50 frames, we can switch to a specific iframe using its particular index number. One can directly switch to the first iframe using the command driver.switchTo().frame(0).
Refer to the sample code:
public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("/URL having iframes/"); //Switch by Index driver.switchTo().frame(0); driver.quit(); }
Switching Frames using Name or ID
A name and Id attribute is always associated with the iframe tag. One can view this by inspecting the page source of a particular web page containing iframes. The image below represents a page source of a sample web page containing iframes.
To switch between an iframe using the name attribute, one can use the switch command as follows:
WebDriver driver = new ChromeDriver(); driver.get("URL”/"); // URL OF WEBPAGE HAVING FRAMES //Switch by frame name driver.switchTo().frame("iframeResult"); //BY frame name driver.quit();
To switch between an iframe using the Id attribute, one can use the switch command as follows:
WebDriver driver = new ChromeDriver(); driver.get("URL”/"); // URL of webpage having frames //Switch by frame name driver.switchTo().frame("iframeResult");// Switch By ID driver.quit();
Switching Frames using WebElement
Another way to switch between frames in selenium is to pass the WebElement to the switchTo() command. Here the primary step is to find the iframe element and then pass it to the switch method.
WebDriver driver = new ChromeDriver(); driver.get("URL”); URL OF WEBPAGE HAVING FRAMES //First finding the element using any of locator stratedgy WebElement iframeElement = driver.findElement(By.id("iframeResult")); //now using the switch command driver.switchTo().frame(iframeElement); driver.quit();
Learn More: Selenium WebElement Commands
Switching back to Main Page
The main page is where all the iframes are embedded. After operating on a particular iframe, use switchTo().parentFrame to move back to the page page. Use switchTo().defaultContent to shift to the primary/first parent frame. Refer to the sample code below:
WebDriver driver = new ChromeDriver(); driver.get("URL");// URL OF WEBPAGE HAVING FRAMES //First finding the element using any of locator strategy WebElement iframeElement = driver.findElement(By.id("iFrameResult")); //now using the switch command to switch to main frame. driver.switchTo().frame(0); //Perform all the required tasks in the frame 0 //Switching back to the main window driver.switchTo().defaultContent(); driver.quit();
The aforementioned methods will help QAs run automated test cases in Selenium faster and with less effort. Simplify and speed up tests further by running them on real devices and browsers.
Testing on Real Device Cloud with BrowserStack Automate
When working with iframes in Selenium, it’s important to test across real user conditions to ensure reliable behavior. BrowserStack Automate enables you to run Selenium tests on a wide range of real iOS and Android devices as well as desktop browsers on their real device cloud.
By using BrowserStack Automate, you can:
- Validate iframe handling across different devices and browsers.
- Ensure iframe-based elements (like embedded widgets or payment gateways) load and function correctly.
- Debug issues faster with access to logs, screenshots, and video recordings of test sessions.
Real device testing ensures your iframe interactions behave consistently across platforms, helping you build more stable, user-ready automation scripts.
Conclusion
Correctly handling iframes is essential for building reliable Selenium test scripts, especially on modern websites that embed dynamic or external content.
Understanding how to switch between frames using different methods, such as index, name/ID, or WebElement, can ensure accurate element interaction.
With real device testing through platforms like BrowserStack Automate, you can validate iframe behavior across browsers and devices, ensuring a seamless user experience.
Useful Resources for Selenium
Methods, Classes, and Commands
- Selenium Commands every Developer or Tester must know
- Selenium WebElement Commands
- Desired Capabilities in Selenium Webdriver
- Assert and Verify Methods in Selenium
- Understanding System setProperty in Selenium
- Select Class in Selenium : How to select a value in dropdown list?
- SendKeys in Selenium WebDriver
- getAttribute() method in Selenium: What, Why, and How to use
- How does Selenium isDisplayed() method work?
- findElement vs findElements in Selenium
- Types of Listeners in Selenium (with Code Examples)
- How to set Proxy in Firefox using Selenium WebDriver?
Configuration
- How to set up Selenium on Visual Studio
- How to configure Selenium in Eclipse
- Maven Dependency Management with Selenium
- How to Build and Execute Selenium Projects
XPath
- How to use XPath in Selenium?
- How to find element by XPath in Selenium with Example
- Top Chrome Extensions to find Xpath in Selenium
Locators and Selectors
- Locators in Selenium: A Detailed Guide
- CSS Selector in Selenium: Locate Elements with Examples
- How to Create Object Repository in Selenium
Waits in Selenium
- Wait Commands in Selenium C and C#
- Selenium Wait Commands: Implicit, Explicit, and Fluent Wait
- Understanding Selenium Timeouts
- Understanding ExpectedConditions in Selenium
- Understanding Role of Thread.sleep() in Selenium
Frameworks in Selenium
- Data Driven Framework in Selenium
- Implementing a Keyword Driven Framework for Selenium: A Practical Guide
- Hybrid Framework in Selenium
Miscellaneous
- How to create Selenium test cases
- How to set Proxy in Selenium?
- Difference between Selenium Standalone server and Selenium server
- Exception Handling in Selenium WebDriver
- How to use JavascriptExecutor in Selenium
- How to run your first Selenium test script
- Parallel Testing with Selenium
Best Practices, Tips and Tricks
- Top 5 Challenges Faced During Automation Selenium Testing
- 5 Selenium tricks to make your life easier
- 6 Things to avoid when writing Selenium Test Scripts
- Best Practices for Selenium Test Automation
- Why you should pay attention to flaky Selenium tests
- How to start with Selenium Debugging
- How to make your Selenium test cases run faster
- How to upgrade from Selenium 3 to Selenium 4
- Why you should move your testing to a Selenium Cloud?
Design Patterns in Selenium: Page Object Model and Page Factory
- Design Patterns in Selenium
- Page Object Model and Page Factory in Selenium
- Page Object Model and Page Factory in Selenium C#
- Page Object Model in Selenium and JavaScript
- Page Object Model and Page Factory in Selenium Python
Action Class
- How to handle Action class in Selenium
- How to perform Mouse Hover Action in Selenium
- Understanding Click Command in Selenium
- How to perform Double Click in Selenium?
- How to Drag and Drop in Selenium?
- How to Scroll Down or Up using Selenium Webdriver
- How To verify Tooltip Using Selenium
TestNG and Selenium
- Database Testing using Selenium and TestNG
- How to use DataProvider in Selenium and TestNG?
- All about TestNG Listeners in Selenium
- How to run parallel test cases in TestNG
- How to use TestNG Reporter Log in Selenium: Tutorial
- Prioritizing tests in TestNG with Selenium
JUnit and Selenium
- Understanding JUnit assertions for Selenium Testing with Examples
- How to run JUnit Parameterized Test in Selenium
- How to write JUnit test cases
- JUnit Testing Tutorial: JUnit in Java
- How to create JUnit Test Suite? (with Examples)
Use Cases
- Handling Login Popups in Selenium WebDriver and Java
- How to Launch Browser in Selenium
- How to handle Alerts and Popups in Selenium?
- How to get Selenium to wait for a page to load
- How to Find Element by Text in Selenium: Tutorial
- How to Read/Write Excel Data using Apache POI Selenium
- How to handle Captcha in Selenium
- How to handle multiple windows in Selenium?
- How to handle Multiple Tabs in Selenium
- How to find broken links in Selenium
- How to handle Cookies in Selenium WebDriver
- How to handle iFrame in Selenium
- How to handle Web Tables in Selenium
- How To Validate Text in PDF Files Using Selenium Automation
- Get Current URL in Selenium using Python: Tutorial
Types of Testing with Selenium
- Different Testing Levels supported by Selenium
- How to perform UI Testing with Selenium
- Regression Testing with Selenium: Tutorial
- UI Automation using Python and Selenium: Tutorial
- How to Run Visual Tests with Selenium: Tutorial
- How to perform ETL Automation using Selenium
- Cross Browser Testing in Selenium : Tutorial