HomebaseWorks
Lesson 2 of 4

Frames, alerts, windows, exceptions and the Page Object Model

How to switch context into frames, alerts and new tabs, what common exceptions mean, and how page objects keep tests maintainable.

EWritten by the HomebaseWorks editorial team · reviewed 26 Oct 2026

WebDriver works in one browsing context at a time. Many confusing failures happen because the test is looking in the wrong place. This lesson covers switching context, reading exceptions and structuring tests.

Advertisement

Switching context

  • Frames: elements inside an iframe cannot be found until you switch in.
driver.switchTo().frame("paymentFrame");   // by name or id
driver.findElement(By.id("cardNumber")).sendKeys("4111...");
driver.switchTo().defaultContent();         // back to the page
  • Alerts: JavaScript alerts are not HTML. Use driver.switchTo().alert(), then accept(), dismiss() or getText().
  • Windows and tabs: the driver stays on the original window. Save the original handle, loop through getWindowHandles(), and switch to the one that differs.
String main = driver.getWindowHandle();
for (String h : driver.getWindowHandles()) {
    if (!h.equals(main)) driver.switchTo().window(h);
}

Common exceptions and what they mean

  • NoSuchElementException: nothing matched. Check the locator, whether the element is in a frame, and whether you waited.
  • StaleElementReferenceException: the element you stored was replaced in the page, often after a refresh or a list update. Find it again rather than reusing the old reference.
  • ElementClickInterceptedException: another element, such as a cookie banner or overlay, is on top. Close it or wait for it to disappear.
  • TimeoutException: an explicit wait's condition never became true within the time limit.

The Page Object Model

In the Page Object Model, each page or component has a class that holds its locators and actions. Tests call those methods and contain only steps and assertions.

public class LoginPage {
    private By email = By.id("email");
    private By password = By.id("password");
    private By submit = By.cssSelector("button[type='submit']");
    public void login(String user, String pass) { ... }
}

When the UI changes, you update one class instead of every test. Keep assertions in the tests, not in page classes, so pages stay reusable.

Where the test framework fits

WebDriver drives the browser. A framework such as TestNG, JUnit or pytest supplies setup and teardown, assertions, grouping and reports. Call driver.quit() in teardown so every browser closes even when a test fails.

Checklist for a new test: stable locators in a page class, explicit waits for each dynamic step, context switched back after frames or windows, and quit in teardown.

Advertisement
Continue with Selenium4 lessons · 1 interview set · 1 test · 1 certificate
Not tested

More in Software testing