Selenium WebDriver is most widely used tool for automating web applications.While automating real-world applications Selenium WebDriver is unable to locate elements in certain situations like : elements inside frames or iframes , elements inside shadow DOM ,dynamic elements.This article helps you understand what are frames, how to handle frames.
What is Frame?
Embedding one page into another webpage called frames. Frames are enclosed in <frame> </frame> tags
In Selenium, frames are used when webpage contains multiple HTML documents embedded in another HTML page.
What is an iframe?
Iframe (inline frame) is an HTML element which is used to embedded other webpage within current webpage. iframe enclosed in <iframe></iframe>
Why Selenium Cannot Locate Elements Inside Frames?
By default, Selenium interacts only with the main webpage DOM. When an element exists inside a frame, it becomes part of a different document context.
So when Selenium searches for an element which is inside frame
driver.findElement(By.id(“xyzzy”));
it searches only in the main page — not inside the frame.
This results in: NoSuchElementException
In order to access elements inside frame we must switch its control to the frame.
Switching Between Frames in Selenium
Selenium provides the switchTo() method to move driver focus into a frame.
Syntax
driver.switchTo().frame();
Different ways to switch Frames
1.Switch Frame Using Index
Syntax: driver.switchTo.frame(indexvalue);
Ex : driver.switchTo().frame(0);
2.Switch Frame Using Name or ID
Syntax : driver.switchTo().frame(“frame name”);
Ex: driver.switchTo().frame(“abc1”);
3.Switch by web Element
Ex: WebElement appframe =driver.findElement(By.id(“abcframe”));
driver.switchTo().frame(appframe);
Switching to Main Page
After completing actions inside frame it should navigate back to main page .
Syntax: 1. driver.switchTo().parentFrame(); : it switches to parent element.
2. driver.switchTo().defaultContent();
Nested Frames: frames inside another frames.
Ex:driver.switchTo().frame(“frameA”);
driver.switchTo().frame(“frameB”);
An Example For Frames
WebDriver driver = new ChromeDriver();
driver.get(” https://dragonflytest.com/”);
// switch to frame
driver.switchTo().frame(“loginFrame”);
// perform action
driver.findElement(By.id(“abc”)).click();
// come back to main page
driver.switchTo().defaultContent();
Conclusion
Since Selenium interacts only with the main DOM by default, automation scripts must explicitly switch driver focus before accessing elements inside frames. Understanding how to identify frames, switch contexts correctly, and return to the main page helps prevent common automation failures and improves script stability.