Introduction
An HTML iframe is used to display a web page within a web page. Most modern web applications might use iframes in some sections. For example, on a Checkout page, the credit card inputs are usually inside an iframe. Endtest allows you to easily interact with elements from iframes.Detect if an element is inside an iframe
We can detect if an element is inside an iframe by inspecting the element with the Chrome Developer Tools. An easier way is to perform a Right Click near the element in your browser and see if theView Frame Source
option is present in the context dropdown.
Interact with an element that is inside an iframe
Since the iframe is a separate web page, we have to tell the test to switch the focus to that iframe before interacting with an element inside it. In theMiscellaneous
action, you have the following methods:
Switch to iframe
Switch back to main
Switch to iframe
when you need to switch focus to the iframe.
When you’re done interacting with the elements from the iframe, use Switch back to main
to switch the focus back to the main web page.
Dealing with nested iframes
There are situations where you might encounter nested iframes (an iframe inside another iframe). The solution is to switch focus to the first iframe, and then to the next one. After you’re done interacting with the elements from the nested iframe, use oneSwitch back to main
step to return the focus to the main web page.
Dealing with iframes that have dynamic IDs
In some cases, an iframe might have a dynamic ID. Since a dynamic ID keeps changing, it isn’t a reliable locator. The solution is to write a custom XPath or CSS Selector for thatSwitch to iframe
step.
The
Switch to iframe
action is using the switch_to
method from Selenium WebDriver. The Switch back to main
action is switching to the default_content
.