How to Handle iframe in Selenium with Java?
Last Updated : 05 Nov, 2024
In this article, we are going to discuss how to handle the iframe in Selenium with Java. The following 6 points will be discussed.
Let's start discussing each of these topics in detail.
What are iframes in Selenium?
Displaying a webpage as a part of another webpage this parameter we called iframe. If the element is present on the main page then we can directly interact and we can perform the actions but when the element is present on the iframe we can not directly interact with those elements. In such cases, we need to change the focus of selenium from the main page to the iframe.
Difference between frame and iframe in Selenium
In Selenium, both frame and iframe elements allow you to embed content or even another web page within the main page. However, there are slight differences also exist which are as follows:
- Frame: A frame is an HTML element that divides the webpage into different sections, each having its own content. It becomes an older element in HTML which is now replaced by more modern methods for creating layouts.
- iFrame: An iframe ( inline frame) is more commonly used today. It allows us to embed external content or another webpage inside our main HTML document. For example, an embedded YouTube video is often placed inside an iframe.
Steps to Identify a Frame on a Page?
There are some methods from which we can identify if there is any iframe present on the webpage or not.
Step 1: Search the iframe on the inspection box
Search the iframe on the inspection boxStep 2: Right-click on that web element
Right-click on that web elementStep 3: Through view page source
Through view page source
How to Switch Over the Elements in iframes using Web Driver Commands?
After identifying the iframe if we need to handle a web element that is present on the iframe, in such cases, we need to change the focus of selenium from the main page to the iframe. There are three different ways to shift the focus of selenium from the main page to the iframe.
Using the SwitchTo().frame function:
The SwitchTo().frame() function is important while working with frames or iframes in Selenium. Before we can interact with elements inside a frame , we must first tell Selenium which frame we want to focus on.
Syntax:
driver.switchTo().frame("frameName")
Once switch into a frame, Selenium will start interacting with the elements inside that frame only.
1. With the help of the index:
We can switch to a frame using its index. The index starts from 0, means the first frame on the page has an index 0, the second frame has an index 1 and so on.
Syntax:
driver.switchTo().frame(index);
driver.switchTo().frame(0);//Switch to the first frame
2. With the help of id/name:
If a frame has a name or ID attribute we can simply switch to it by using that name or ID.
Syntax:
driver.switchTo().frame("frameNameOrID");
here we need to identify the id value or name value from the HTML codes of the iframe.
This method is more reliable than switching by index because name and IDs typically remain static , even if the structure of page changes.
driver.switchTo().frame("loginFrame"); // to switch to thr frame with the name ' loginFrame'
3. With the help of web element
Syntax:
driver.switchTo().frame(webelement);
here we need to declare a webelement by using attributes of iframe.
How to Switch back to the Main iframe?
Suppose we need to change the focus of selenium from iframe to the main page or parent iframe for which there are two different ways.
- driver.switchTo().parentFrame(); - We use this method to change the focus of selenium from one iframe to parent iframe (previous iframe)
driver.switchTo().defaultContent();
- driver.switchTo().defaultContent(); - We use this method to change the focus of selenium from one iframe to the main page.
For performing the automation we will create a webpage by using HTML. Here are the HTML codes for creating a webpage with an iframe.
driver.switchTo().parentFrame();
HTML <!DOCTYPE html> <html> <head> <style> .gfg {width:200px} .gfgiframe {width:400px; height:200px; background-color:#98FB98} </style> </head> <body> <center> <h1 style="color:#32CD32">GeeksforGeeks</h1> <form> Name : <input class="gfg" type="text" id="name"/> <br> <br> Email : <input class="gfg" type="text" id="email" /> </form> <br> <iframe class="gfgiframe" id="gfgiframe" src="Provide the path of your iframe webpage"> </iframe> <br> <br> Contact : <input class="gfg" type="text" id="contact" /> <br> <br> <input type="button" value="Submit" id="submit" style="width:100px;background-color:#gray"/> </center> </body> </html>
For the iframe, we used another webpage and provided its URL in src. The HTML codes of the iframe are given below.
HTML <!DOCTYPE html> <html> <head></head> <body> <center> <br> <br> <form> <textarea type="text" rows="8" style="width:350px" id="Textmessage" placeholder="Message"> </textarea> </form> </center> </body> </html>
Webpage Output:
Layout of Webpage
Here we have to submit some of the information on the Geeksforgeeks page.
- Name
- Email
- Message
- Contact No.
Now let’s see the script for automating the webpage and to fill in the information by using Java.
Program 1: To handle the web element of a single iframe ( switching the focus of selenium by using an index )
To switch the focus of selenium from the main page to the iframe, here we are going to use the index method.
Syntax:
driver.switchTo().frame(index number);
It’s a first iframe and we know that index count starts with zero. So we will give the index number as zero(0). To switch back to the main frame we will use driver.switchTo().parentFrame(); method
Java import java.time.Duration; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class GFG_Iframe { public static void main(String[] args) { // Using chrome as a browser System.setProperty("webdriver.chrome.driver"," Path of Chromedriver.exe"); // Webdriver object WebDriver driver = new ChromeDriver(); // We have created one webpage by using html driver.get("Provide your webpage link"); // To maximize the page driver.manage().window().maximize(); // To delete all the cookies driver.manage().deleteAllCookies(); // Providing implicit wait driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15)); //Enter name by id driver.findElement(By.id("name")).sendKeys("Suraj Bade"); // Enter E-mail with xpath driver.findElement(By.xpath("//input[@id='email']")).sendKeys("[email protected]"); // Switching the focus of selenium from main page to iframe // we are using index here driver.switchTo().frame(0); // Enter a message text driver.findElement(By.xpath("//textarea[@id='Textmessage']")).sendKeys("Thank you for creating such a knowledgeable platform. "); // Switching the focus of selenium from iframe to main page driver.switchTo().parentFrame(); // to enter the contact number driver.findElement(By.xpath("//input[@id='contact']")).sendKeys("0102030405"); // Enter contact with xpath driver.findElement(By.xpath("//input[@id='submit']")).click(); // to close the tab driver.quit(); } }
Output:
Program 2: To handle the web element of a single iframe ( switching the focus of selenium by using id or name )
To switch the focus of selenium from the main page to the iframe, here we are going to use the id/name method.
Syntax:
driver.switchTo().frame("value");
In HTML codes we can check the id value/name value. here id value is given as gfgiframe. we will use this value in our method. To switch back to the main frame we will use driver.switchTo().parentFrame(); method
Java import java.time.Duration; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class GFG_Iframe { public static void main(String[] args) { // Using chrome as a browser System.setProperty("webdriver.chrome.driver"," Path of Chromedriver.exe"); // Webdriver object WebDriver driver = new ChromeDriver(); // We have created one webpage by using html driver.get("Provide your webpage link"); // To maximize the page driver.manage().window().maximize(); // To delete all the cookies driver.manage().deleteAllCookies(); // Providing implicit wait driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15)); // Enter name by id driver.findElement(By.id("name")).sendKeys("Suraj Bade"); // Enter E-mail with xpath driver.findElement(By.xpath("//input[@id='email']")).sendKeys("[email protected]"); // Switching the focus of selenium from main page to iframe // we are using id value here driver.switchTo().frame("gfgiframe"); // Enter a message text driver.findElement(By.xpath("//textarea[@id='Textmessage']")).sendKeys("Thank you for creating such a knowledgeable platform. "); // Switching the focus of selenium from iframe to main page driver.switchTo().parentFrame(); // to enter the contact number driver.findElement(By.xpath("//input[@id='contact']")).sendKeys("0102030405"); // Enter contact with xpath driver.findElement(By.xpath("//input[@id='submit']")).click(); // to close the tab driver.quit(); } }
Output:
Program 3: To handle the web element of a single iframe ( switching the focus of selenium by using webelement )
To switch the focus of selenium from the main page to the iframe, here we are going to use webElement method.
Syntax:
driver.switchTo().frame(webElement);
Here first we declare a webElement by using the attributes of iframe and then we will pass that webelement in above method. To switch back to main frame we will use driver.switchTo().parentFrame(); method
Java import java.time.Duration; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class GFG_Iframe { public static void main(String[] args) { // Using chrome as a browser System.setProperty("webdriver.chrome.driver","Path of chromedriver.exe"); // Webdriver object WebDriver driver = new ChromeDriver(); // We have created one webpage by using html driver.get("provide your webpage link"); // To maximize the page driver.manage().window().maximize(); // To delete all the cookies driver.manage().deleteAllCookies(); // Providing implicit wait driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15)); //Enter name by id driver.findElement(By.id("name")).sendKeys("Suraj Bade"); // Enter E-mail with xpath driver.findElement(By.xpath("//input[@id='email']")).sendKeys("[email protected]"); // declaring a webelement from the attributes of iframe WebElement gfg = driver.findElement(By.xpath("//iframe[@id='gfgiframe']")); //Switching the focus of selenium from main page to iframe driver.switchTo().frame(gfg); // Enter a message text driver.findElement(By.xpath("//textarea[@id='Textmessage']")).sendKeys("Thank you for creating such a knowledgeable platform. "); // Switching the focus of selenium from iframe to main page driver.switchTo().parentFrame(); // to enter the contact number driver.findElement(By.xpath("//input[@id='contact']")).sendKeys("0102030405"); // Enter contact with xpath driver.findElement(By.xpath("//input[@id='submit']")).click(); // to close the tab driver.quit(); } }
Output:
How to handle nested iframe in selenium webDriver
We will use HTML codes for designing the nested iframe
HTML codes for the main page:
HTML <!DOCTYPE html> <html> <head> <style> .gfg {width:200px} </style> </head> <body> <center> <h1 style="color:#32CD32">GeeksforGeeks</h1> Statement 1 : <input class="gfg" type="text" id="Statement1"/> <br> <br> <iframe class="gfgiframe" id="gfgiframe" width="600" height="300" src="Provide the path of iframe1 webpage"> </iframe> <br> <br> Statement 4 : <input class="gfg" type="text" id="Statement4" /> <br> <br> </center> </body> </html>
HTML codes for the iframe1:
HTML <!DOCTYPE html> <html> <head> <style> .gfg {width:200px} </style> </head> <body> <center> <h2 style="color:Black">Iframe 1 </h2> Statement 2 : <input class="gfg" type="text" id="Statement2"/> <br> <br> <iframe class="gfgiframe2" id="gfgiframe2" width="500" height="120"src="Provide the path of iframe2 webpage"> </iframe> </center> </body> </html>
HTML codes for the iframe2:
HTML <!DOCTYPE html> <html> <head> <style> .gfg {width:200px} </style> </head> <body> <center> <h2 style="color:Black">Iframe 2 </h2> Statement 3 : <input class="gfg" type="text" id="Statement3"/> <br> <br> </center> </body> </html>
Webpage Output:
Layout of WebpageHere we can observe,
- Statement 1 and Statement 4 are located on main page.
- Statement 2 located on iframe 1 and Statement 3 is located on iframe 2.
- iframe 1 is located inside iframe 2.
Program 3: To handle the web element of nested iframe
Java import java.time.Duration; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class GFGNestedIframe { public static void main(String[] args) { // we are using chrome driver System.setProperty("webdriver.chrome.driver","Path of chromedriver.exe"); // Webdriver object WebDriver driver = new ChromeDriver(); // etering the URL driver.get("Provide your webpage link"); // to maximize the window driver.manage().window().maximize(); // to delete all cookies driver.manage().deleteAllCookies(); // Providing implicit wait driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15)); //Giving text input in Statement1 driver.findElement(By.xpath("//input[@id='Statement1']")).sendKeys("My Statement 1"); // Switching the focus of selenium from main page to iframe1 driver.switchTo().frame(0); // Giving text input in Statement2 driver.findElement(By.xpath("//input[@id='Statement2']")).sendKeys("My Statement 2"); // Switching the focus of selenium from iframe1 to iframe2 driver.switchTo().frame(0); // Giving text input in Statement3 driver.findElement(By.xpath("//input[@id='Statement3']")).sendKeys("My Statement 3"); // Switching the focus of selenium from iframe2 to main page driver.switchTo().defaultContent(); // Giving text input in Statement4 driver.findElement(By.xpath("//input[@id='Statement4']")).sendKeys("My Statement 4"); } }
Output:
Explanation:
We can directly identify Statement 1 as it is located on the main page but for Statement 2 we need to switch the focus of selenium from the main page to iframe 1. So we will use driver.switchTo().frame(); method with index zero. Now the focus of selenium is on iframe 1 so we can directly identify Statement 2 but for Statement 3 we again need to switch the focus of selenium from iframe 1 to iframe 2. So we will again use driver.switchTo().frame(); method with index zero, Now the focus of selenium is on iframe 2 so we can directly identify Statement 3. For locating the Statement 4 we need to switch the focus of selenium from iframe 2 to main page, so here we will use the driver.switchTo().defaultContent(); method.
Conclusion
The key thing to remember that before interacting with any elements inside an iFrame , we first switch to that iframe using driver.switch().frame(). We can also switch by index, name or ID, depending on the available attributes.And If we want to switch back to the main content we can use driver.switchTo().defaultContent(). which will ensures smooth interaction across different sections of our webpage.
Similar Reads
How to handle Frames/iFrames in Selenium with Python
Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python. HTML outlines are utilized to isolate yo
2 min read
How to Handle Alert in Selenium using Java?
Imagine filling out a form online and accidentally missing some information. You only know if you made a mistake if the website tells you somehow, like with a pop-up message. This article explains what those pop-up messages are called in Selenium (alerts) and how to deal with them in your automated
6 min read
How to click on an image using Selenium in Java?
Selenium, a popular tool for automating web application testing across browsers, often requires image interaction. In this article we will discuss how to clicking on image using Selenium in Java. PrerequisitesJava Development Kit (JDK) installed.Selenium WebDriver library added to your project.A sup
3 min read
How to disable images in chrome using Selenium java?
Disabling images in Chrome during automated testing can enhance performance and speed up your Selenium tests. This is particularly useful when dealing with large web pages or when you want to focus on specific elements without the distraction of images. In this guide, we'll walk you through how to d
2 min read
How to find the src of an image in Selenium java?
Selenium WebDriver is a popular automation tool used for testing web applications across different browsers. One common task in web automation is extracting information from web elements, such as retrieving the src attribute of an image. The src attribute holds the URL of the image, and Selenium pro
4 min read
How to download File in Selenium Using java
Automating the file download process is essential in web automation testing, especially for validating functionalities involving document downloads such as PDFs, images, or CSV files. However, Selenium WebDriver doesnât directly handle file downloads. To overcome this limitation, we can configure th
2 min read
How to handle multiple windows in Selenium?
Handling multiple windows in Selenium is crucial when dealing with web applications that open new tabs or windows during interactions. Whether you're testing applications with pop-ups, modals, or new browser tabs, Selenium WebDriver provides efficient methods to switch between multiple windows or ta
8 min read
How to download Google Image Using java Selenium?
Downloading images from Google using Java Selenium is a task that can come in handy for various automation projects. Whether you're building a dataset for machine learning, collecting images for research, or simply want to automate the process of downloading images, Selenium provides a robust soluti
5 min read
How to convert commands recorded in Selenium IDE to Java?
Selenium IDE is a powerful browser extension allowing you to record and replay interactions easily. However, for more advanced testing and integration with frameworks like JUnit, it is essential to convert recorded commands into Java code. In this guide, we will walk you through converting Selenium
6 min read
How to upload a file in Selenium java with no text box?
Uploading a file in Selenium Java without a visible text box can be easily handled using the sendKeys() method. Even if the file input field is hidden or styled as a button, Selenium allows you to interact with it by providing the file path directly. This method simplifies the process of file upload
3 min read