What is IFrame?
  • IFrame (Inline Frame) is an HTML document embedded inside current HTML Webpage.
  • Frame behaves like an inline image, it can be configured with its own scrollbar independent of the surrounding page's scrollbar.
Why Web Designers use IFrame's?
  • By using Iframe's, developer can insert content from other source(Ex: advertisements, third party images content etc) into your web page.
  • By enabling Javascript developer can change/update the iframe content without requiring the user to reload the surrounding page.

Handling Frames using Selenium webdriver:
We can observe/identify iframes in html like 
<iframe></iframe>” tag.By using Selenium, we cannot interact/validate the web-elements directly which are inside the iframe tags.

Example:





Before performing any action/validation inside the iframe(above example), we need to switch to iframe.For this we need to use  swtichTo().frame command.There are three ways to switch to frame in selenium.
  1. By Index based:
    • By passing the frame number, we can switch inside the frame.
    • Select a frame by its (zero-based) index. That is, if a page has multiple frames (more than 1), the first frame would be at index "0", the second at index "1" and so on
    • Parameters: Index - (zero-based) index
    • Sample Code:
      driver.switchTo().frame(0);//want to switch to 1 frame
      driver.switchTo().frame(1);//want to switch to 2 frame
  1. By FrameName Or Id based:
    • By Passing the frame element Name or ID and driver will switch to that frame.
    • Parameters: name Or Id - the name of the frame or the id of the frame element
    • Sample Code:
      driver.switchTo().frame("f1");//if want to switch by using frame name=”f1”
      driver.switchTo().frame("addvert");//if want to switch by using frame id=”addvert”
  1. By WebElement based:
    • By passing the frame web element and driver will switch to that frame
    • Parameters: frameElement - The frame element to switch to
    • Sample Code:
driver.switchTo().frame(By.xpath("//iframe"));//if want to switch by using web-elements.

Selenium Code to handle multiple nested frames:

driver.switchTo().frame("Parent FrameName").switchTo().frame("child framename or id or index");


Selenium Code to switch out of frames:

  • In order to switch back from frame there is that will help us
  • In a web page two iFrames are embedded. Once you are done with all the task in a particular iFrame you can switch back to the main web page using the switchTo().defaultContent()
  • Sample code:

    driver.switchTo().defaultContent();
    
Categories: