image of iFrame in Selenium

How to handle iFrame in Selenium

iFrame is the most commonly used HTML Element to display or embed a complete web page into a new window. The iFrame element is used in all modern websites and has many advantages over other types of coding. iFrame comes with many benefits.

Over the years, many websites have used iFrame. Despite it being a common practice these days, browsers still view iFrames with suspicion and don’t allow any 1×1 DIVs inside an iframe. Still, Modern web development recommends not to use the iFrame or suggests using it only when there are no alternatives due to security concerns around the iFrame elements.

What is an iFrame?

You will see many websites using a large number of iFrames on their pages. This is because it provides several benefits that web developers look forward to. But before going into detail, let us see what an iFrame element is and how it can help you with mechanisms like Selenium.

An iFrame is also known as simply Frame or Inline Frame, where an HTML document loads another webpage within the HTML document. All major browsers support iFrame. The standard function of iFrame in websites is to embed the resources such as videos, images, or other content.

When the browser sees an iFrame element, it renders as a separate HTML page and embeds into the parent. The major challenge with iFrame is if you simply try to get the element and perform an operation on that, the automation tools will not be able to handle them. So you need to use a different mechanism like Selenium WebDriver to handle iFrame.

Advantages of iFrame

1. The complete webpage can be embedded using the iFrame

2. The iFrame can load any third-party resources without any additional configurations.

3. Updating content is more manageable if you have multiple pages embedded into a single webpage using an iframe. You can simply update the reference pages and view changes reflected on the parent page.

4. The iFrame can be nested, which means you can have iFrame inside another iFrame

5. Iframe content can be made as lazy loading, which means you can load the iFrame content only required.

Disadvantages of iFrame

1. The webpage which is having iFrame is challenging to automate. Nested iFrame makes automation more complicated.

2. The nested dynamic iFrames with no unique identification will be difficult to automate, and tests will become flaky and unreliable.

3. Having multiple iFrames in a single webpage makes the web page ugly and less responsive.

4. Some browsers have limited support for the iFrame, so the browser which provides limited support will be unable to display the content inside the iFrame

5. The iFrames are not mobile-friendly. If you want to display the content in the mobile browser, you should avoid using iFrames. Some mobile browsers even restrict the iFrame content.

6. A framework built on iFrame will increase the HTTP requests, increasing the server load, which is not recommended.

Security Concerns with iFrame

iFrame simply loads the targeted page, which doesn’t check for vulnerabilities, so if the embedded page has security concerns, then your webpage is at risk. The same is applicable when you load the resources using iFrames—considering the security concerns, and the modern web development frameworks suggest not to use until and unless there are no alternatives.

Challenges with Automation 

Handling the iFrame requires a different mechanism than the typical style of automating the web elements. Many automation tools have limitations around automating the iFrames. 

The selenium provides an integrated mechanism to handle the iFrame. Even with selenium, you might see flaky tests if your website has nested iFrame. You can also explore other alternatives for selenium that you can find helpful

Example of IFrame

As you can see in the above image, The iFrame is an HTML subpart inside The main HTML. The main HTML document and iFrame both have HTML and a body tag.

How to ensure the element is iFrame?

When you inspect the element in the browser and find the tag name <iframe>, or parent tag as a <iframe>, the page contains the IFrame. 

How to handle the iFrame element in Selenium?

Selenium is a beloved automation tool in the automation industry. It provides techniques to automate all possible scenarios for handling iframe. 

selenium provides a special command. driver.switchTo().frame()

The driver.switchTo().frame() helps to identify and perform the actions on elements inside the iFrame.

Selenium provides multiple ways to switch over to iFrame

1. ID

2. Name

3. Index

4. WebElement

Selenium Switch to iFrame using ID

The most common and efficient way to switch to iFrame in selenium is using the frame id. Where iFrame is associated with id or name.

The syntax for switching the iFrame using frameID

Syntax:

Driver.switchTo.frame(“<frame_id”)

Example:

Consider the above image. You can find the Click Me button inside the iFrame. Typically you will get the frame linked for the button and perform the action on the element. This mechanism works if the button is not inside the iFrame. In case you want to perform any operations on an element inside the iFrame, you need to switch to that iFrame to get access to its HTML elements.

To perform the actions on the Element inside the iFrame, follow the below steps.

1. Switch to iFrame

2. Perform the action on iFrame Element

3. Switch to the Main window

Let’s understand in detail

First, Switch to iFrame using the frame id, i.e. iframeResult

driver.switchTo().frame(“iframeResult”);

Identify the Element inside the iFrame, that is button.

WebElement element = driver.findElement(By.tagName(“button”));

Click on the element 

element.click();

Post that, switch the context to the main window.

driver.switchTo().defaultContent();

The above steps make a complete flow of actions. If you put together the above code, it looks like the below.

     driver.switchTo().frame(“iframeResult”);

     WebElement element = driver.findElement(By.tagName(“button”));

     element.click();driver.switchTo().parentFrame();

driver.switchTo().defaultContent();

Switching between iFrames and Main Page in Selenium

Consider, the scenario you have nested iFrame like below

The parenetFrame() in Selenium

In the above image, the Main window has iFrame1, the iFrame 1 as another iFrame in it that is iFrame 2.  The driver.switchTo().parentFrame(); always switches to the immediate parent frame depending on the frame you are working in.

For example, if you are inside the iFrame2, then driver.switchTo().parentFrame();, switches the context to iFrame1, similarly if you are in the iFrame1 then calling driver.switchTo().parentFrame(); switches the context to Main window or main page

Syntax: 

driver.switchTo().parentFrame();

The defaultContent(); in Selenium

The driver.switchTo().defaultContent(); in selenium helps to switch the context to top most frame which is main page. Regardless of your current context, you can switch to the main page using the driver.switchTo().defaultContent(); switches the context back to the main page automatically. i.e if your context is in iFrame1 then calling the driver.switchTo().defaultContent (); switches to main page.

Syntax: 

driver.switchTo().defaultContent();

To summarize

driver.switchTo().parentFrame(); : Switches control to parent frame

driver.switchTo().defaultContent(); : Switches control to topmost page.

Switch to iFrame in Selenium using frame name

The frame name and frame id work nearly in a similar way, where instead of the frame id, you can specify the frame name.

Syntax:

driver.switchTo().frame(“<frame_name”);

Example: 

HTML Code

<div id=”modal”>

  <iframe id=”buttonframe” name=”myframe”  src=”https://seleniumhq.github.io”>

   <button>Click here</button>

 </iframe>

</div>

In the above HTML code, you can see the iFrame has the name myframe, you can switch to this iFrame by specifying the name

driver.switchTo().frame(“myframe”);

then, you can execute the action on the element inside the Iframe.

The complete code cycle will look like this.

     driver.switchTo().frame(“myframe”);

     WebElement element = driver.findElement(By.tagName(“button”));

     element.click();

Find the Total Number of Frames on the webpage

There are scenarios where you might need to get the iFrame count of the webpage. This is mostly useful when your webpage has multiple iFrames.

There are two ways to get the number of iFrames on the Webpage.

1. Get the total number of iFrames Selenium using Javascript Executor

JavascriptExecutor jse = (JavascriptExecutor) driver;

Integer numberOfFrames = Integer.parseInt(jse.executeScript(“return window.length”).toString());

  System.out.println(“Number of iframes on the page are ” + numberOfFrames);

In the above code, we are using the JavascriptExecutor to get the count of iFrame inside the webpage, The window.length in JavaScript executor returns the count of iFrame. 

2. Get the count of iFrame inside the webpage using Selenium Find Elements  method

List<WebElement> iframeElements = driver.findElements(By.tagName(“iframe”));

System.out.println(“The total number of iframes are ” + iframeElements.size());

In the second method, we are using the driver.findElements() methods, which returns the list of elements having tagName iFrame.  Once you get the list, you can calculate the list size, which is the total number of iFrames present on the webpage, using the size() method i.e iframeElements.size();

Switch to iFrame by Index

Your webpage might have embedded iFrame, which might not have any unique property to identify such as frame name, frame id, etc., then the only option is to use the index to switch the context to iFrame.

The index starts from 0; the first iFrame is index 0, so switching to the 0th index makes it switch to iFrame 1. 1st index switches to iFrame 2, etc.

Syntax: 

driver.switchTo.frame(“<frame_index>”)

Note: The frame index is always integer

Let’s consider we have HTML code like below

<div id=”modal”>

  <iframe> 

   <button>Click here</button>

 </iframe>

</div>

Consider the above HTML code, that doesn’t have any HTML attributes such as id, name, etc. so in such case you can switch the context to iFrame using an index. In the above case, you can switch the context like below 

driver.switchTo.frame(0)

If you have multiple frames, you can use indexes like 1, 2, 3, etc.

Once you switch to iFrame, you will have access to all the elements inside that iFrame. On which you can execute the action.

The complete code looks like the one below.

     driver.switchTo().frame(0);

     WebElement element = driver.findElement(By.tagName(“button”));

     element.click();

Switch to iFrame using WebElement

Selenium provides multiple options, including the use of web elements. Using the Web element technique, you must first locate the web Element of the iFrame using driver.findElement() then you can specify the element in driver.switchTo().frame() command.

Let’s see how we can use it.

Consider you have HTML code like the below.

In the above HTML code, the <div id=’iframewrapper”> is having the iFrame tag, so you need to get the web element of iFrame considering that

WebElement element = driver.findElement(By.xpath(“//div[@id=’iframewrapper’]/iframe”));

Next, Switch to Frame

  driver.switchTo().frame(element);

Now, you can perform the actions with the HTML elements inside the IFrame

String text = driver.findElement(By.tagName(“h1”)).getText();

The complete code looks like below

     WebElement element = driver.findElement(By.xpath(“//div[@id=’iframewrapper’]/iframe”));

     driver.switchTo().frame(element);

     String text = driver.findElement(By.tagName(“h1”)).getText();

     System.out.println(“The text inside the iFrame is ” + text);

Handling Nested Iframes in Selenium

As mentioned previously, the iFrame can be nested, which means an Iframe can hold another completely valid iFrame.

Consider the above image, You have an iFrame with id iframeResult, and there is one more iFrame inside that iFrame. Now, if you want to access the h1 inside the second iFrame but you can’t directly access it.

If you want to access the element <h1> This page is displayed in an iframe </h1>  First, you need to switch the context to iFrame1 is iFrame “iframeResult” , and then the second iFrame.

Switch to First iFrame

driver.switchTo().frame(“frame result”);

Switch to Second iFrame

driver.switchTo().frame(0);

Note: The index 0 refers to inside the parent iFrame, the first iFrame, so when you give index 0 it switches to the first iFrame.

Now, Get the h1 text using the tag name name

String text = driver.findElement(By.tagName(“h1”)).getText();

The complete code looks like below

     driver.switchTo().frame(“iframeResult”);

     driver.switchTo().frame(0);

     String text = driver.findElement(By.tagName(“h1”)).getText();

     System.out.println(“Text inside the nested iFrame”+text);

Key take away

1. Selenium provides multiple options to switch the context to iFrame such as index, id, name, and web element.

2. The driver.switchTo.frame() method is used to switch the context to iFrame.

3. You can get the total count of iFrame either by using JavaScriptExecutor or the findElementsbyTagName() method.

4. When there are no unique attributes associated with iFrame, you can use the frame index switch to the frame using the frame index

5. The driver.switchTo().parentFrame();  is used for switching the context to the parent frame.

6. driver.switchTo().defaultContent();  is used for switching context to topmost page.

7. Automating nested iFrame requires switching the context to a different iFrame

The future for software testing is not fading away, it is evolving in a very positive and effective direction. Modern web applications are changing rapidly and becoming more complex, making the skillset that testers need to develop more important than ever.

Frameworks like Selenium work as a backbone for most test automation frameworks. The real challenge of a framework is at times it becomes too complex and does not offer the flexibility to manage test cases in any manner easily.

Alternatively, there are other frameworks like Katalon, which require the user to write code for every step that needs to be taken. The scalable and support options offered by Testsigma act as a great relief from the challenges faced by testers and developers alike.

 By combining the “Human-Readable Tests” with the power of automation, modern automation frameworks like Testsigma can help drive the need for a skilled workforce while also increasing their efficiency in development.

Testsigma understands the challenges of the modern automation world, and the solution was built after carefully analyzing the challenges in the automation world. Testsigma provides testing web applications across multiple platforms and browser combinations. So the tests that are written in TestSigma can be run on Mobile, Desktop, Chrome, Firefox, etc.


Test automation made easy

Start your smart continuous testing journey today with Testsigma.

SHARE THIS BLOG

RELATED POSTS