Selenium and Java

Tuesday, 4 August 2015

Selenium - Handling multiple iFrames in Selenium Webdriver

An inline frame is used to embed another document within the current HTML document. It means iframe is actually a webpage within the webpage which have its own DOM for every iframe on the page.

Once the frame is selected or navigated , all subsequent calls on the WebDriver interface are made to that frame. i.e the driver focus will be now on the frame. What ever operations we try to perform on pages will not work and throws element not found as we navigated / switched to Frame.
We can select an iFrame using the below metthods:

1. by index: frame(index):  We can use index of the frame to get focus on the frame. index start with 0. 

   driver.switchTo().frame(0) ;// focus on 0th frame

   Parameters: Index - (zero-based) index
   Returns: driver focused on the given frame (current frame)
   Throws: NoSuchFrameException - If the frame is not found.

2. by name : frame(Name of Frame) : We can use name of the frame instead of index to get frame.

      driver.switchTo().frame(frameName) ;// focus on frame with name frameName

    Parameters: name Or Id - the name of the frame or the id of the frame element.
    Returns: driver focused on the given frame (current frame)
   Throws: NoSuchFrameException - If the frame is not found

3. by Id: frame(Id of the frame): We can also use Id of the frame as below

  driver.switchTo().frame(frameID) ;// focus on frame with ID as frameId

    Parameters: name Or Id - the name of the frame or the id of the frame element.
    Returns: driver focused on the given frame (current frame)
   Throws: NoSuchFrameException - If the frame is not found

4. by locating frame like other element: frame(WebElement frameElement)

  First locate frame with any web element locator and use webelement.

 Webelement el = driver.findelement(by.xpath(".//iframe[@title='ABC']"));
 driver.switchTo().frame(el);

    Parameters: frameElement - The frame element to switch to.
    Returns: driver focused on the given frame (current frame).
    Throws: NoSuchFrameException - If the given element is neither an iframe nor a frame element. And StaleElementReferenceException - If the WebElement has gone stale.

5. switching outside frame : defaultContent()

  driver.switchTo().defaultContent();

6. switch to multiple frame : 

driver.switchTo().frame(ParentFrame).switchTo().frame(ChildFrame);

1 comment: