Software Dev and QA Tips

How Do You Handle iFrames in Selenium Webdriver: Switchto()?

Written by Timothy Joseph | May 17, 2021 4:00:00 PM

iFrames in Selenium are also referred as the inline frame. An inline frame is used to embed any other document within the current/parent HTML document using <iframe></iframe> tags.

Iframes are mainly utilized to insert data from different external sources. For example, if a third party advertisement is displayed on a web page and we need to move that advertisement to a specific position, it can be accomplished using iframe.

Below is the syntax of iframe declared in HTML (DOM)

<html>
<body>
<div class="names">
<iframe name="iframe1" id="IF1"</iframe>
</div>
<div class="names">
<iframe name="iframe2" id="IF2"></iframe>
</div>
</body>
</html>

To handle the iframe in Selenium WebDriver: switchTo():

SwitchTo().frame method primarily enables the browser to switch between multiple frames.  SwitchTo() can be implemented in the following ways:

  1. driver.switchTo.frame(int iframe number) - This method allows the web driver to switch to a specific frame using its index, for example- switchTo.frame(2);
  2. driver.switchTo.frame(string frameNameOrId) - This method allows the web driver to switch to a particular frame using the defined frame name, for example- switchTo.frame("iframe1");
  3. driver.switchTo.frame(WebElement element) - This method allows the web driver to switch to a certain frame based on the location of the web element

Example -

WebElement element = driver.findElement(By.id("IFrame1")); switchTo.frame(element);

Switching to Main Page:

After performing different operations on a particular page, we can switch back to the main page using - switchTo().defaultContent();

We can also use the default method in the ExpectedCondition class to switch on any iframe (if a particular frame is not found then NoSuchFrameException will be thrown):

WebDriverWait wait = new WebDriverWait(driver, 10);
driver.switchTo().defaultContent();
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath(locator)));