How to work with IFrame in Selenium. – User friendly Tech help

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

n

n

n

n

n

n

n

Learn to solve the iFrame puzzle in selenium

n

nSolution:-
nLets try to understand iFrame first.
n
nWhat is iFrame?
nAn 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)
n
nHow it is handled in Selenium?
nAs 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”.
n
nPrinciple:-
nSelenium 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.
n
nSyntax:-
nSwitching to the frame: 

n

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

n

                  
nSwitching back to the parent window: 

n

driver.switchTo().defaultContent();

n

nApproach:-
nUsing find element Technique,

n

//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"); ;

n

  
n   
nUsing Index of the Frame,    

n

driver.switchTo().frame(0);

n

n0- refers the first child frame.
n
nUsing name/id of the frame

n

driver.switchTo().frame(“framename”);

n

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

n

Code:-

Was this article helpful?
YesNo

Similar Posts