Working with iFrames in Selenium for Java
Working with iFrames in Selenium for Java
Learn how to work with iFrames using Selenium for Java
Today’s recipe will focus on working with iFrames in Selenium.
Here we have an iFframe within our website, and we can see that this iFframe actually hosts the table. So, what we want to do is to interact with this table, maybe sort it by name.
Let’s see how we can do this with Selenium.
How to Test iFrames with Selenium Using switchTo Method
To access an iFrame, we first use our WebDriver object and we say driver.switchTo().
From there, we can switch to a frame and notice that there are 3 overloaded methods for frames.
One method takes the String nameOrId attribute of the frame.
The second method takes an index, and this is the position that that frame exists in the website. The indexes do start at zero (0). If you wanted to access the first frame, you would enter 0. If you wanted to access the second frame, you would enter 1, and so on.
And if you already have a handle to the frame via a WebElement, then you can pass that in and switch to the frame there.
Let’s go ahead and say that we want the one that takes the String, which is the name, or the ID, and we’ll go back to our website to get this information.
We see that our iFrame does have an ID of “the-kitchen-table”, so we’ll get this and put it in our code.
How to Perform an Action in an iFrame with Selenium
We have switched context from the main website’s DOM to this iFrame. What this means is now we can navigate or do any interaction, but only inside of that frame.
Let’s go and look at it again. So, this is the frame that we’re within, and this is the context that we are boxed into right now.
Okay, we want to click on this column. Let’s go ahead and find that ID. This is the button ID, “column-button-name”. Let’s grab that.
Inside of our code, we can say driver.findElement(), and we can specify the ID that we have. Then we can say go ahead and click() that.
How to Switch Out of iFrame with Selenium
Now let’s say that we want to get outside of this frame, right? We want to do some more things on the main website.
Remember we’re already within the context of the frame; we can’t access anything that’s outside of this frame until we do a driver.switchTo() and go back to the .parentFrame().
This will remove us from the context of that frame and put us back in the main DOM. Once we’re in the parentFrame, we can continue with anything else on the page.
If we wanted to switch to yet another frame, we could do that. Or if we just want it to operate within the main DOM, we could do that as well.
Okay, that covers iFrames. Hopefully this has been helpful. See you next time.
Resources
- Git Repo – FrameTests.java
- Applitools Kitchen – Testing iFrames
Schedule a free Applitools Demonstration
Request DemoHere’s the code sample from our tutorial on how to work with iFrames using Selenium for Java