How to work with IFrame in Selenium.

Scenario:
Our application has a iFrame control, how we can work with this control using Selenium.

Bird thinking about iframe selenium
Learn to solve the iFrame puzzle in selenium


Solution:-
Lets try to understand iFrame first.

What is iFrame?
An iFrame (or Inline Frame) is an HTML document embedded inside the current HTML document on a browser application. It is utilized to insert content from another source, such as an advertisement, into a Web page. Our application can have multiple frames on a single page, which can be further nested (Frame inside a Frame). This enables updates of parts of a website while the user browses, without making them reload the whole thing. (This is now largely replaced by AJAX)

How it is handled in Selenium?
As we know iFrame works as an independent application inside a parent application .Thus to work with iFrame elements , we need to change the focus of selenium from parent window to the iFrame window(child window).If we are not doing this, selenium won’t be able to identify controls of iFrame and we will face “ElementNotFoundExceptions”.

Principle:-
Selenium WebDriver works with multiple windows(iFrame here) using window handler.It assigns an unique alphanumeric id to each window as soon as the WebDriver object is instantiated. Further with the help of this id it switchs control among several windows. In simple terms, each unique window has a unique ID, so that Selenium can differentiate when it is switching controls from one window to the other.

Syntax:-
Switching to the frame: 

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

                  
Switching back to the parent window: 

driver.switchTo().defaultContent();


Approach:-
Using find element Technique,

//First we will find the iFrame , then we will switch to command.
WebElement frame = driver.findElement(By.Name("frame1"));
// or
WebElement frame = driver.findElement(By.Id("frame1"))
//Now we will switch focus,
driver.switchTo().frame("frame"); ;

  
   
Using Index of the Frame,    

driver.switchTo().frame(0);


0- refers the first child frame.

Using name/id of the frame

driver.switchTo().frame(framename);

Note:-
GetWindowHandle Command , to get the window handle of the current window.
String  hnd = driver.getWindowHandle();

Code:-

Leave a Reply

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