Blogs

Get useful information on apps testing and development

Handling iFrames in Selenium Based Test Automation

An iFrame is commonly known as an inline frame which is nothing but an HTML document embedded inside another HTML document. iFrames are a simpler way to embed a web page inside another web page. iFrames are mostly used to display external information on the webpage like displaying advertisements and videos from third party sources.

 

iFrame is basically a tag used in HTML5 like <iframe></iframe>. For example, let’s have a look at the below screenshot where the Customer Chat Service pop up has been aligned by pCloudy on a web page as a iFrame

 

 

 

As a point to highlight, there’s a difference between iFrame and Frame in Selenium. While the iFrames are used to embed content from external sources, the frames leverage developers to split the web page vertically or horizontally with the frameset tags.

How To Identify iFrames on a Web Page?

Looking at the web page and identifying the iframes is definitely not possible. So the question is, how to identify whether an element is on an iframe or not? You just have to right click on the suspected element and check whether you are getting an option such as : ‘This Frame’, ‘View Frame Source’ or ‘Reload Frame’. After right clicking on an element, if you get an option related to frames, that simply means, the element you are trying to locate is aligned on an iframe.

 

In the above screenshot, after right clicking on the Customer Chat pop up, we see the options to ‘view frame source’ and ‘reload frame’, hence we can be sure that the targeted element is on an iframe.

 

There might be a possibility that a parent web page embeds multiple iframes. In such a case, you can open the browser dev tools and checkout the required iframe by searching the keyword ‘iframe’ under ‘Elements’ tab of dev tools.

With Selenium based test automation, you can also get the count of iframes on a particular web page with a below code snippet :

 

int iFrameSize = driver.findElements(By.tagName(“iframe”)).size();

How to Switch Selenium Webdriver to Elements over iFrame?

To switch over the elements and handle the web iframes in selenium, the Selenium framework offers 3 common ways:

  • Switch To iFrame By Index : Switching to iframe using index is probably used when there are multiple iframes present on a single web page. Index of iframe starts with 0 and the index gets increasing with the number of iframes embedded. If there are 2 iframes present on a web page, you can use below code snippet to switch to iframes in Selenium :

driver.switchTo().frame(0);
driver.switchTo().frame(1);

  • Switch To iFrame By Name or ID : Name and ID attribute is the most common way of switching to iframe using Selenium. You can easily fetch either the name or ID of the iframe from the browser dev tools.

In the above screenshot of a pCloudy homepage, you can find an iframe with both name and id in the browser dev tool. To locate targeted element over iframe using name or id, the below code snippet can be used :

driver.switchTo().frame(“iFrameID”); OR driver.switchTo().frame(“iFrameName”);

  • Switch To iFrame By Web Element : Another way of switching to iframe using Selenium is to use the Web Element in the switchTo() command. Here the idea is to get the iframe element from browser dev tools and pass it to the switch method. To locate targeted element over iframe using web element, the below code snippet can be used :

WebElement iframeElement = driver.findElement(By.id(“webElementID”)); driver.switchTo().frame(iframeElement);

How to Switch the Selenium Webdriver Back to the Main Frame?

Not all elements of the web page are aligned on an iframe. As discussed earlier, iframes are majorly used to display external applications, videos or advertisements. As a part of Web test automation, you may find a scenario where all the major operations are being performed on a parent web page, but to just click on another specific element you have to switch to the targeted frame and switch back to the parent frame so that the webdriver can continue its operation on the main webpage.

To switch back the Selenium Webdriver to the main frame, Selenium offers two in-built methods :

  1. parentFrame()

  2. defaultContent()

Code snippet :

driver.switchTo().parentFrame(); driver.switchTo().defaultContent();

Switching over the iFrame when iFrame ID, Name and Web Element doesn’t work or isn’t present

The common questioned scenario : how to handle iframes in Selenium when iframe ID, Name and Web Element doesn’t work or isn’t present?

Let’s imagine that there are 100 iframes embedded on a single web page and there is no iframe id or name available. In the case of 100 iframes, suspecting the index of iframe is also a complex task. Hence, we have to adopt some strategy that could identify the iframe of the targeted element.

As a resolution to the above scenario, it is important to fetch out the index of the iframe on which the targeted element is being loaded and then we can switch to the iframe using it’s index. Let’s have a look at the below script and code walkthrough to automate such scenarios.

public class SeleniumIframe { public static void main(String[] args) {

WebDriver driver = new ChromeDriver(); driver.get(“URL“); driver.manage().window().maximize(); int iFrameSize = driver.findElements(By.tagName(“iframe”)).size(); for(int i=0; i<=iFrameSize; i++){ driver.switchTo().frame(i); int elementSize = driver.findElements(By.xpath(“html/body/a/advertVideo”)).size(); System.out.println(elementSize); driver.switchTo().defaultContent(); } } }

Code Walk through :

Since there are multiple iframes embedded on a single web page, we have used a tagName Selenium locator to get the total number of iframes present. Once we are aware of the actual iframe count, we have started a loop till the size of the iframe. And in a running loop, we are switching to each iframe present on the web page and fetching the size of the targeted element. Whenever the loop gets executed for the correct iframe, we would get the element size as 1 else size of the web element would remain 0.

This way, we could extract the index of the iframe. Once we get the exact index of the iframe, we can then comment the loop to avoid running against every iframe embedded on the web page.

Handling Nested iFrames in Selenium Test Automation

Let’s assume that the targeted element is on an iframe aligned on another iframe, this kind of structure is known as nested iframes.

 

 

 

Looking at the above image, there are two frames, one iframe inside another iframe. The targeted element is aligned under iframe 2. This means, in selenium test automation, we first have to interact with the iframe1, then with the iframe 2 to perform operation on the targeted web element. Below is the HTML structure of nested iframe where the second iframe tag is embedded in the first iframe tag.

 

<div class=“iframe”>
<
div style=“overclow:auto;”>
<
div id=“iframewrapper” class=“iframewrapper”>
<
iframe id=“iframeResult” frameborder=“0”>
<
html>
<
head>
<
body>
<
iframe width=“200” height=“200” src=“demo_iframe.htm”>
</
body>
</
head>
</
html>

In the test automation scenario of nested iframes, the mandate steps that needs to be followed are:

 

  • Firstly, we need to switch to the outer frame, either by name, ID or index

  • After switching to the outer iframe, we can fetch the count of inner iframes in selenium

  • We can then switch to the inner frame with any of the available type i.e ID, name or index

  • Lastly, we can interact with the targeted element.

Advantages of using iframes in Selenium automation

  • Isolation: Iframes provide a way to isolate content within a web page. This can be useful when dealing with third-party widgets, advertisements, or elements from different domains. Selenium can interact with elements inside iframes independently, without affecting the main page.

  • Modular Testing: Websites often use iframes to load dynamic content, such as videos, forms, or maps. By handling iframes, you can create more modular test cases, focusing on specific functionalities within the iframe without worrying about the entire page.

  • Reusability: Iframes can be reused across multiple pages or scenarios, allowing you to write code for interacting with the iframe once and then reuse it as needed. This promotes code reusability and maintainability.

  • Parallel Testing: When you need to perform parallel testing, iframes can help by enabling you to run multiple tests concurrently, each interacting with a different iframe. This can improve test execution speed and efficiency.

  • Enhanced Debugging: Debugging can be easier when you isolate problematic elements within iframes. You can narrow down issues to specific iframes and inspect their contents separately, simplifying the troubleshooting process.

  • Improved Performance: By interacting with elements within iframes, you can avoid loading unnecessary resources from the main page, potentially improving the performance of your automated tests.

  • Enhanced Security: Iframes provide a level of security by isolating content from different origins. Selenium can interact with elements within iframes while maintaining the security boundaries established by the web browser.

  • Testing Cross-Domain Scenarios: If your application involves cross-domain interactions (e.g., embedding content from different domains), iframes allow you to test these scenarios effectively.

 

Challenges while working with iframes

 

While iframes offer several advantages in Selenium automation, they also introduce complexities that require careful handling. It’s crucial to assess whether using iframes is necessary for your testing scenario and to implement robust and maintainable automation code when working with them. Here are some of the challenges that automation testers will need to keep in mind while handling iFrames –

  • Context Switching: You’ll need to switch the Selenium driver’s context to the iframe you want to interact with, and then switch back to the main page when done. This context switching can add complexity to your automation scripts.

  • Handling Nested Iframes: When iframes are nested within one another, managing the context and switching between them can become more complex.

  • Identifying Elements: Identifying elements within iframes may require unique locators, as elements inside iframes have a separate DOM hierarchy. Careful selection of locators is essential to ensure reliable automation.

  • Handling Dynamic Iframes: Some websites dynamically load iframes, making it challenging to predict when they will appear or disappear. You may need to implement logic to handle such cases.

 

Conclusion

 

Understanding how iframes work will help in accurately targeting the right web elements we want to test using Selenium automation. We have discussed various ways by which we can use iframes in the selenium test automation.

Automate with Selenium

Automate your web app testing by running your selenium scripts on multiple real desktop browsers with ease.

Shivani Sinha

She is a Product Marketer with over 9 years of diversified experience across content, branding, and product marketing. Her experience ranges from global brands to nimble startups. She is a custodian of Brand & Content, telling stories about the brand that delights customers and provides compelling business value.