Software Development and QA Tips

Dev and QA Tips How Do You Handle iFrames in Selenium Webdriver: Switchto()?

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

Selenium iFrames | By Vakul Gotra | May 17, 2021

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

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

Disclaimer

This publication is for informational purposes only and nothing contained in it should be considered legal advice. We expressly disclaim any warranty or responsibility for damages arising out of this information and encourage you to consult with legal counsel regarding your specific needs. We do not undertake any duty to update previously posted materials.