Jobs Platform
Selenium with Java and TestNG: Level 1

Lesson 5 of 8 · 9 min

Alerts, frames and multiple windows

Some parts of a web page are outside the main document that Selenium looks at. JavaScript pop-ups, pages inside frames, and new tabs each need a switch. Selenium works with only one context at a time, and you must move it yourself.

JavaScript alerts

A JavaScript alert, confirm or prompt box is not part of the HTML, so findElement cannot see it. Use switchTo().alert(). Wait for it first, because it may appear a moment after the click.

driver.findElement(By.id("alertBtn")).click();
Alert alert = new WebDriverWait(driver, Duration.ofSeconds(5))
    .until(ExpectedConditions.alertIsPresent());
System.out.println(alert.getText());
alert.accept();
Hello
  • accept() presses OK.
  • dismiss() presses Cancel on a confirm box.
  • getText() reads the message.
  • sendKeys(text) types into a prompt box.

If an alert is open and you try to use the page, Selenium throws UnhandledAlertException. Handle the alert first.

Frames

An iframe is a page placed inside another page. Elements inside it are invisible to findElement until you switch into the frame. This is a common reason for NoSuchElementException when the element is clearly on the screen.

driver.switchTo().frame("frame1");          // by id or name
driver.findElement(By.id("inner")).click();
System.out.println(driver.findElement(By.id("inner")).getText());
driver.switchTo().defaultContent();            // back to main page
System.out.println(driver.findElement(By.id("heading")).getText());
Clicked
Practice Page

You can also pass a WebElement or an index to frame(). Use parentFrame() to go up one level when frames are nested, and defaultContent() to return to the top page. Once you switch into a frame, elements outside it cannot be found until you switch back.

Windows and tabs

Selenium treats windows and tabs the same way. Each has a handle, a unique string. When a click opens a new tab, the browser shows it, but your driver stays on the old one. You have to switch.

String original = driver.getWindowHandle();
driver.findElement(By.id("newTab")).click();
new WebDriverWait(driver, Duration.ofSeconds(5))
    .until(ExpectedConditions.numberOfWindowsToBe(2));
for (String handle : driver.getWindowHandles()) {
    if (!handle.equals(original)) {
        driver.switchTo().window(handle);
    }
}
System.out.println(driver.getTitle());
driver.close();                         // closes the new tab only
driver.switchTo().window(original);     // you must switch back
System.out.println(driver.getTitle());
Second
Practice Page

After close(), the driver still points at the closed tab. If you do not switch back to a valid handle, the next command fails with NoSuchWindowException. Selenium 4 also lets you open a tab yourself: driver.switchTo().newWindow(WindowType.TAB) creates a new tab and switches to it.

Try it yourself

  • Create an HTML page with a button that shows alert('Hi'). Read and accept the alert.
  • Create a page with an iframe containing a button. Click the button, then print a heading from the main page.
  • Write a link with target="_blank" and switch to the new tab. Print its title and close it.
  • Call newWindow(WindowType.TAB), open a site in it, and print the number of handles.

Quick check

Three quick questions on this lesson. Your answers are not saved.

  1. Question 1 of 3

    After a click, a JavaScript alert is showing. Which line gets control of it?

  2. Question 2 of 3

    You finished work inside an iframe and need the main page again. Which call do you use?

  3. Question 3 of 3

    What does driver.getWindowHandles() return?