We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Switching contexts to interact with elements inside iframes.
An iframe is like a small, separate web page embedded inside the main page. Selenium can only “see” and interact with elements in one context at a time.
If your element lives inside an iframe and you don’t switch into it first, Selenium will act like the element doesn’t exist.
switchTo().frame("id"): Best option. Switch by ID or Name.switchTo().frame(element): Switch using a WebElement found on the page.switchTo().frame(0): Switch by index (fragile).switchTo().defaultContent(): Jumps back to the top-level page.switchTo().parentFrame(): Moves one level up (for nested frames).<iframe>. You MUST switch to the frame first!You must switch contexts to interact with the form inside the dashed border!
1234567891011121314151617// Part 1: Interact INSIDE the iframe
driver.switchTo().frame("practiceFrame");
WebElement emailInput = driver.findElement(By.id("emailInput"));
emailInput.clear();
emailInput.sendKeys("student@example.com");
WebElement saveEmailBtn = driver.findElement(By.id("saveEmailBtn"));
saveEmailBtn.click();
// Part 2: Go back to MAIN page and interact there
driver.switchTo().defaultContent();
WebElement outsideButton = driver.findElement(By.id("outsideButton"));
outsideButton.click();
driver.quit();findElement() calls are scoped inside this frame.defaultContent().After finishing work in a frame, call defaultContent() immediately. Leaving focus in a frame is a common cause of test flakiness.
Prefer wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(...)) so you wait for the frame and switch to it in one step.
frame(0) is fragile. If a new ad or analytics iframe is added at the top of the page, your index will point to the wrong frame.