iFrame switching (switchTo.frame) in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Duration; public class IframeSwitchTest { private WebDriver driver; private WebDriverWait wait; @BeforeEach public void setUp() { driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); } @Test public void testIframeText() { driver.get("https://example.com/page-with-iframe"); // Wait for iframe to be available and switch to it wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("frame1"))); // Wait for paragraph inside iframe WebElement paragraph = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("iframe-text"))); // Verify the text inside iframe String actualText = paragraph.getText(); assertEquals("Hello from iframe!", actualText, "Iframe paragraph text should match"); // Switch back to main content driver.switchTo().defaultContent(); // Verify main page title (example) String title = driver.getTitle(); assertEquals("Example Page", title, "Main page title should be correct"); } @AfterEach public void tearDown() { if (driver != null) { driver.quit(); } } }
This test opens the webpage with an iframe. It waits explicitly until the iframe with id 'frame1' is ready, then switches into it using frameToBeAvailableAndSwitchToIt. Inside the iframe, it waits for the paragraph with id 'iframe-text' to be visible, then reads its text and asserts it matches the expected string.
After checking the iframe content, the test switches back to the main page using driver.switchTo().defaultContent(). It then verifies the main page title to confirm the switch back was successful.
Setup and teardown methods initialize and close the browser cleanly. Explicit waits ensure the test is stable and does not fail due to timing issues.
Now add data-driven testing to verify paragraph text inside iframes with 3 different iframe ids and expected texts.