---
description: What is Iframe? A web page which is embedded in another web page or an HTML document embedded inside another HTML document is known as a frame. The IFrame is often used to insert content from another
title: How to Handle iFrames in Selenium Webdriver: switchTo()
image: https://www.guru99.com/images/how-to-handle-iframes-in-selenium-webdriver.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

Handle iFrames in Selenium WebDriver shows how testers control HTML frames inside pages, covering identification, switching context, nested handling, and stability techniques.

* 🖼️ **iFrame Basics:** Embeds one HTML document inside another.
* 🔍 **Identify:** Use dev tools or findElements(By.tagName).
* 🔁 **switchTo:** Switch by index, name, ID, or WebElement.
* 🪜 **Nested:** parentFrame and defaultContent move back up.
* ⚠️ **Stability:** Wait before switchTo to avoid exceptions.
* 🤖 **AI Helpers:** AI generates robust iFrame locators.

[ Read More ](javascript:void%280%29;) 

![How to Handle iFrames in Selenium WebDriver](https://www.guru99.com/images/how-to-handle-iframes-in-selenium-webdriver.png)

## iFrame in Selenium Webdriver

**iFrame in Selenium Webdriver** is a web page or an inline frame which is embedded in another web page or an HTML document embedded inside another HTML document. The iframe is often used to add content from other sources like an advertisement into a web page. The iframe is defined with the <**iframe**\> tag.

## How to identify the iFrame

We cannot detect the frames by just seeing the page or by inspecting Firebug.

Observe the below image, Advertisement being displayed is an Iframe, we cannot locate or recognize that by just inspecting using Firebug. So the question is how can you identify the iframe?

[](https://www.guru99.com/images/Sap-QM/122315%5F0943%5FHandlingIfr1.png)

How to identify the iframe using Selenium WebDriver

We can identify the frames in Selenium using methods given below:

* Right click on the element, If you find the option like ‘This Frame’ then it is an iframe.(Please refer the above diagram)
* Right click on the page and click ‘View Page Source’ and Search with the ‘iframe’, if you can find any tag name with the ‘iframe’ then it is meaning to say the page consisting an iframe.

In above diagram, you can see that ‘**This Frame**‘ option is available upon right clicking, so we are now sure that it is an iframe.

We can even identify total number of iframes by using below snippet.

Int size = driver.findElements(By.tagName("iframe")).size();

## How to Handle Frames in Selenium using WebDriver Commands

Basically, we can switch over the elements and handle frames in Selenium using 3 ways.

* **By Index**
* **By Name or Id**
* **By Web Element**

### Method 1: Switch to the frame by index

Index is one of the attributes for frame handling in Selenium through which we can switch to it.

Index of the iframe starts with ‘0’.

Suppose if there are 100 frames in page, we can switch to frame in Selenium by using index.

* `driver.switchTo().frame(0);`
* `driver.switchTo().frame(1);`

### RELATED ARTICLES

* [Selenium Webdriver Java Program Example ](https://www.guru99.com/first-webdriver-script.html "Selenium Webdriver Java Program Example")
* [How to Select Date from DatePicker/Calendar in Selenium Webdriver ](https://www.guru99.com/handling-date-time-picker-using-selenium.html "How to Select Date from DatePicker/Calendar in Selenium Webdriver")
* [How to Handle Dynamic Web Tables in Selenium ](https://www.guru99.com/handling-dynamic-selenium-webdriver.html "How to Handle Dynamic Web Tables in Selenium")
* [Locators in Selenium ](https://www.guru99.com/locators-in-selenium.html "Locators in Selenium")

### Method 2: Switch to the frame by Name or ID

Name and ID are attributes for handling frames in Selenium through which we can switch to the iframe.

* `driver.switchTo().frame("iframe1");`
* `driver.switchTo().frame("id of the element");`

**Example of Switching to iframe through ID:**

 to the frame by Web Element

We can access this iframe through this below URL: <https://demo.guru99.com/test/guru99home/>

[](https://www.guru99.com/images/Sap-QM/122315%5F0943%5FHandlingIfr2.png)

It is impossible to click iframe directly through[ XPath ](https://www.guru99.com/xpath-selenium.html)since it is an iframe. First we have to switch to the frame and then we can click using xpath.

**Step 1)**

WebDriver driver = new FirefoxDriver();

driver.get("https://demo.guru99.com/test/guru99home/");

driver.manage().window().maximize();

* We initialise the Firefox driver.
* Navigate to the “guru99” site which consist the iframe.
* Maximized the window.

**Step 2)**

driver.switchTo().frame("a077aa5e");

* In this step we need to find out the id of the iframe by inspecting through Firebug.
* Then switch to the iframe through ID.

**Step 3)**

driver.findElement(By.xpath("html/body/a/img")).click();

* Here we need to find out the xpath of the element to be clicked.
* Click the element using web driver command shown above.

**Here is the complete code:**

public class SwitchToFrame_ID {
public static void main(String[] args) {

		WebDriver driver = new FirefoxDriver(); //navigates to the Browser
	    driver.get("https://demo.guru99.com/test/guru99home/"); 
	       // navigates to the page consisting an iframe

	       driver.manage().window().maximize();
	       driver.switchTo().frame("a077aa5e"); //switching the frame by ID

			System.out.println("********We are switch to the iframe*******");
     		driver.findElement(By.xpath("html/body/a/img")).click();
  		    //Clicks the iframe
       
  			System.out.println("*********We are done***************");
      }
}		

**Output:**

Browser navigates to the page consisting the above iframe and clicks on the iframe.

### Method 3: Switch to the frame by Web Element

We can even switch to the iframe using web element .

* `driver.switchTo().frame(WebElement);`

**How to switch back to the Main Frame**

We have to come out of the iframe.

To move back to the parent frame, you can either use switchTo().parentFrame() or if you want to get back to the main (or most parent) frame, you can use switchTo().defaultContent();

	    driver.switchTo().parentFrame();
	    driver.switchTo().defaultContent();

**How to switch over the frame, if we CANNOT switch using ID or Web Element:**

Suppose if there are 100 frames in the page, and there is no ID available, in this case, we just don’t know from which iframe required element is being loaded (It is the case when we do not know the index of the frame also).

The solution for the above concern is, we must find the index of the iframe through which the element is being loaded and then we need to switch to the iframe through the index.

Below are the steps for finding the index of the Frame by which the element is being loaded by using below snippet

**Step 1)**

WebDriver driver = new FirefoxDriver();
driver.get("https://demo.guru99.com/test/guru99home/");
driver.manage().window().maximize();

* Initialise the Firefox driver.
* Navigate to the “guru99” site which consisting the iframe.
* Maximized the window.

**Step 2)**

int size = driver.findElements(By.tagName("iframe")).size();

* The above code finds the total number of iframes present inside the page using the tagname ‘iframe’.

**Step 3)**

**Objective for** this step would be finding out the index of iframe.

for(int i=0; i<=size; i++){
	driver.switchTo().frame(i);
	int total=driver.findElements(By.xpath("html/body/a/img")).size();
	System.out.println(total);
	    driver.switchTo().defaultContent();}

Above “forloop” iterates all the iframes in the page and it prints ‘1’ if our required iframe was found else returns ‘0’.

**Here is the complete code till step 3:**

public class IndexOfIframe {
public static void main(String[] args) {
	    WebDriver driver = new FirefoxDriver();
	    driver.get("https://demo.guru99.com/test/guru99home/");  
	    driver.manage().window().maximize();
	    //driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
	    int size = driver.findElements(By.tagName("iframe")).size();

	    for(int i=0; i<=size; i++){
		driver.switchTo().frame(i);
		int total=driver.findElements(By.xpath("html/body/a/img")).size();
		System.out.println(total);
	    driver.switchTo().defaultContent();}}}

**Execute this program and output would be like below:**

**Output:**

1
0
0
0	
0
0

Verify the output, you can find the series of 0’s and 1’s.

* Wherever you find the ‘1’ in output that is the index of Frame by which the element is being loaded.
* Since the index of the iframe starts with ‘0’ if you find the 1 in the 1stplace, then the index is 0.
* If you find 1 in 3rd place, the index is 2.

We can comment out the for loop, once we found the index.

**Step 4)**

driver.switchTo().frame(0);

* Once you find the index of the element, you can switch over the frame using above command.
* driver.switchTo().frame(index found from the Step 3);

**Step 5)**

driver.findElement(By.xpath("html/body/a/img")).click();

* The above code will clicks the iframe or element in the iframe.

**So the complete code would be like below:**

public class SwitchToframe   {
public static void main(String[] args) throws NoSuchElementException{
	    WebDriver driver = new FirefoxDriver();
	    driver.get("https://demo.guru99.com/test/guru99home/");  
	    driver.manage().window().maximize();
	    //int size = driver.findElements(By.tagName("iframe")).size();
	
	/*for(int i=0; i<=size; i++){
	    driver.switchTo().frame(i);
	    int total=driver.findElements(By.xpath("html/body/a/img")).size();
		System.out.println(total);
	    driver.switchTo().defaultContent(); //switching back from the iframe
	 }*/
	            
		//Commented the code for finding the index of the element
	    driver.switchTo().frame(0); //Switching to the frame
		System.out.println("********We are switched to the iframe*******");
		driver.findElement(By.xpath("html/body/a/img")).click();
		
		//Clicking the element in line with Advertisement
	    System.out.println("*********We are done***************");
	        }
	    }

**Output:**

Browser navigates to the page consisting the above iframe and clicks on the iframe.

## Concept of Nested Frames in Selenium

Let’s assume that there are two frames one inside other like shown in below image and our requirement is printing the text in the outer frame and inner frame.

**In the case of nested frames,**

* At first we must switch to the outer frame by either Index or ID of the iframe
* Once we switch to the outer frame we can find the total number of iframes inside the outer frame, and
* We can switch to the inner frame by any of the known methods.

While exiting out of the frame, we must exit out in the same order as we entered into it from the inner frame first and then outer frame.

**The Html code for the above nested frame is as shown below.**

[](https://www.guru99.com/images/Sap-QM/122315%5F0943%5FHandlingIfr4.png)

The above HTML code clearly explains the iframe tag (highlighted in green) within another iframe tag, indicating presence of nested iframes.

Below are the steps for switching to outer frame and printing the text on outer frames:

**Step 1)**

 WebDriver driver\=new FirefoxDriver(); driver.get("Url"); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS); int size = driver.findElements(By.tagName("iframe")).size(); System.out.println("Total Frames --" \+ size); // prints the total number of frames driver.switchTo().frame(0); // Switching the Outer Frame System.out.println (driver.findElement(By.xpath("xpath of the outer lkw">element ")).getText()); 
* Switch to the outer Frame.
* Prints the text on outer frame.

Once we switch to the outer frame, we should know whether any inner frame present inside the outer frame

**Step 2)**

size = driver.findElements(By.tagName("iframe")).size();
    // prints the total number of frames inside outer frame           
    System.out.println("Total Frames --" + size);

* Finds the total number of iframes inside outer frame.
* If size was found ‘0’ then there is no inner frame inside the frame.

**Step 3)**

driver.switchTo().frame(0); // Switching to innerframeSystem.out.println(driver.findElement(By.xpath("xpath of the inner lkw">element ")).getText()); 
* Switch to the inner frame
* Prints the text on the inner frame.

**Here is the complete code:**

public class FramesInsideFrames { public static void main(String\[\] args) { WebDriver driver\=new FirefoxDriver(); driver.get("Url"); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS); int size = driver.findElements(By.tagName("iframe")).size(); System.out.println("Total Frames --" \+ size); // prints the total number of frames driver.switchTo().frame(0); // Switching the Outer Frame System.out.println (driver.findElement(By.xpath("xpath of the outer lkw">element ")).getText()); //Printing the text in outer framesize = driver.findElements(By.tagName("iframe")).size(); // prints the total number of frames inside outer frame System.out.println("Total Frames --" \+ size); driver.switchTo().frame(0); // Switching to innerframeSystem.out.println(driver.findElement(By.xpath("xpath of the inner lkw">element ")).getText()); //Printing the text in inner frame driver.switchTo().defaultContent(); } } 

**Output**:

The output of the above code would print the text in the Inner frame and Outer frame.

## FAQs

⚡ Frame vs iFrame?

Frames are deprecated. iFrames embed a single document inside any page.

🤖 How AI helps iFrame tests?

AI suggests locators and self-heals flaky indexes.

💡 Can AI detect iFrame elements?

Yes. AI inspects the DOM and injects the right switchTo.

🔁 Return to main page?

Use switchTo().defaultContent() or parentFrame().

⚠️ Why NoSuchFrameException?

iFrame missing or stale. Add explicit waits.

🔍 Count iFrames?

driver.findElements(By.tagName(“iframe”)).size().

🛡️ Cross-origin iFrames?

switchTo works. Some JavaScriptExecutor calls may fail.

📚 Time to master?

Basics one day. Nested frames one to two weeks.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/how-to-handle-iframes-in-selenium-webdriver.png","url":"https://www.guru99.com/images/how-to-handle-iframes-in-selenium-webdriver.png","width":"700","height":"250","caption":"How to Handle iFrames in Selenium Webdriver","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/handling-iframes-selenium.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/selenium","name":"Selenium"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/handling-iframes-selenium.html","name":"How to Handle iFrames in Selenium Webdriver: switchTo()"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/handling-iframes-selenium.html#webpage","url":"https://www.guru99.com/handling-iframes-selenium.html","name":"How to Handle iFrames in Selenium Webdriver: switchTo()","dateModified":"2026-06-23T16:02:53+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/how-to-handle-iframes-in-selenium-webdriver.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/handling-iframes-selenium.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/admin","name":"Krishna Rungta","url":"https://www.guru99.com/author/admin","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/krishna-rungta-v2-120x120.png","url":"https://www.guru99.com/images/krishna-rungta-v2-120x120.png","caption":"Krishna Rungta","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Selenium","headline":"How to Handle iFrames in Selenium Webdriver: switchTo()","description":"What is Iframe? A web page which is embedded in another web page or an HTML document embedded inside another HTML document is known as a frame. The IFrame is often used to insert content from another","keywords":"selenium","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/admin","name":"Krishna Rungta"},"dateModified":"2026-06-23T16:02:53+05:30","image":{"@id":"https://www.guru99.com/images/how-to-handle-iframes-in-selenium-webdriver.png"},"copyrightYear":"2026","name":"How to Handle iFrames in Selenium Webdriver: switchTo()","subjectOf":[{"@type":"HowTo","name":"How to Handle Frames in Selenium using WebDriver Commands","description":"Basically, we can switch over the elements and handle frames in Selenium using 3 ways.","step":[{"@type":"HowToStep","name":"Step 1) Switch to the frame by index:","text":"Index is one of the attributes for frame handling in Selenium through which we can switch to it.","url":"https://www.guru99.com/handling-iframes-selenium.html#step1"},{"@type":"HowToStep","name":"Step 2) Switch to the frame by Name or ID:","text":"Name and ID are attributes for handling frames in Selenium through which we can switch to the iframe.","url":"https://www.guru99.com/handling-iframes-selenium.html#step2"},{"@type":"HowToStep","name":"Step 3) Switch to the frame by Web Element:","text":"We can even switch to the iframe using web element.","url":"https://www.guru99.com/handling-iframes-selenium.html#step3"}]},{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Frame vs iFrame?","acceptedAnswer":{"@type":"Answer","text":"Frames are deprecated. iFrames embed a single document inside any page."}},{"@type":"Question","name":"How AI helps iFrame tests?","acceptedAnswer":{"@type":"Answer","text":"AI suggests locators and self-heals flaky indexes."}},{"@type":"Question","name":"Can AI detect iFrame elements?","acceptedAnswer":{"@type":"Answer","text":"Yes. AI inspects the DOM and injects the right switchTo."}},{"@type":"Question","name":"Return to main page?","acceptedAnswer":{"@type":"Answer","text":"Use switchTo().defaultContent() or parentFrame()."}},{"@type":"Question","name":"Why NoSuchFrameException?","acceptedAnswer":{"@type":"Answer","text":"iFrame missing or stale. Add explicit waits."}},{"@type":"Question","name":"Count iFrames?","acceptedAnswer":{"@type":"Answer","text":"driver.findElements(By.tagName(\"iframe\")).size()."}},{"@type":"Question","name":"Cross-origin iFrames?","acceptedAnswer":{"@type":"Answer","text":"switchTo works. Some JavaScriptExecutor calls may fail."}},{"@type":"Question","name":"Time to master?","acceptedAnswer":{"@type":"Answer","text":"Basics one day. Nested frames one to two weeks."}}]}],"@id":"https://www.guru99.com/handling-iframes-selenium.html#schema-249270","isPartOf":{"@id":"https://www.guru99.com/handling-iframes-selenium.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/handling-iframes-selenium.html#webpage"}}]}
```
