Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 35 ยท Interacting with the Page

Alerts, Frames and Windows

Learn how Selenium switches context: handling JavaScript alerts, working inside iframes, and moving between windows and tabs with window handles.

Your script talks to exactly one place at a time, called the current context. At the start it is the top-level page in the window you opened. Some things on a real site live elsewhere: a JavaScript alert that blocks the page, a payment form inside an iframe, a link that opens in a new tab. A locator that is perfectly correct fails with NoSuchElementException when the script is looking at the wrong context, and this is one of the most common reasons beginners get stuck.

This lesson teaches you to see that context and change it with driver.switch_to. You will handle alerts, move into and out of frames, and control windows and tabs using window handles.

Selenium and a browser cannot run on this site, so the Selenium code is read-only. The runnable examples are JavaScript stand-ins that model a browser's windows, frames and alert as a small tree, so you can see how the context changes.

Alerts, confirms and prompts

JavaScript offers three dialogs: alert() (a message and OK), confirm() (OK and Cancel) and prompt() (a text box). While one is open the page is blocked, and most other commands fail with UnexpectedAlertPresentException. Switch to the alert to deal with it:

Python
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

driver.find_element(By.ID, "delete").click()

alert = WebDriverWait(driver, 5).until(EC.alert_is_present())
print(alert.text)        # the message
alert.accept()           # press OK

alert.dismiss() presses Cancel, and alert.send_keys("text") types into a prompt before you accept it. driver.switch_to.alert returns the alert immediately and raises NoAlertPresentException when there is none, which is why waiting for alert_is_present() is safer: the dialog may take a moment to appear after the click.

The dialog belongs to the browser, not to the page content, so locators cannot find it. The newer in-page "modal" dialogs that many sites draw with HTML and CSS are normal elements, not alerts: locate and click them as usual. A quick test is whether you can inspect the dialog in DevTools; if you can, it is not an alert.

Where is the script looking?

Window A tab or window has a handle.
Frame An iframe is a page inside a page.
Alert A browser dialog that blocks the page.

Locators only search the current context.

1 / 2

Frames and iframes

An <iframe> embeds another document inside the page. Payment widgets, rich-text editors and embedded videos often use them. The embedded document has its own DOM, and find_element on the main page does not see inside it. You must enter the frame first:

Python
driver.switch_to.frame("card-frame")                 # by id or name
driver.switch_to.frame(0)                            # by index (position on the page)
frame_el = driver.find_element(By.CSS_SELECTOR, "iframe[title='Card number']")
driver.switch_to.frame(frame_el)                     # by element (the most precise)

driver.find_element(By.NAME, "cardnumber").send_keys(TEST_CARD_NUMBER)  # a test value from your sandbox

driver.switch_to.default_content()                   # back to the main page

Use a frame element or an id, not an index; an index changes when a new frame is added. Frames can be nested: switch_to.frame goes one level deeper from where you are, switch_to.parent_frame() goes up one level and switch_to.default_content() jumps all the way back to the top. A wrong frame is the main cause of "the element is clearly there but Selenium cannot find it". Check the page source (or DevTools) for an enclosing iframe.

You can wait for a frame to be ready and enter it in one step with EC.frame_to_be_available_and_switch_to_it((By.ID, "card-frame")).

Windows and tabs

Each window or tab has a handle, an opaque string such as CDwindow-4F2A.... You can read them:

Python
main = driver.current_window_handle        # where you are now
all_handles = driver.window_handles        # a list of every open window or tab

When a click opens a new tab, the driver stays on the old one. You must find the new handle and switch to it. Because the handle list does not promise an order, find the new one by comparing with what you had before:

Python
before = set(driver.window_handles)
driver.find_element(By.LINK_TEXT, "Terms (opens in a new tab)").click()

WebDriverWait(driver, 5).until(EC.number_of_windows_to_be(len(before) + 1))
new_handle = (set(driver.window_handles) - before).pop()

driver.switch_to.window(new_handle)
print(driver.title)

driver.close()                        # closes only the current tab
driver.switch_to.window(main)         # you MUST switch back; nothing is selected now

Selenium 4 also lets you open your own window: driver.switch_to.new_window("tab") (or "window") opens it and switches to it in one call.

Two things trip people up here. First, driver.close() closes the current window but leaves the session alive and the context undefined: the next command raises NoSuchWindowException until you call switch_to.window(...). Second, driver.quit() ends the whole session and closes every window; call it once at the end, not in the middle of a test.

sequenceDiagram
    participant T as Test
    participant D as Driver
    participant B as Browser
    T->>D: click link (target blank)
    D->>B: click
    B-->>D: new tab opens
    Note over D: still on the old handle
    T->>D: window_handles
    D-->>T: [main, new]
    T->>D: switch_to.window(new)
    D->>B: select tab

A new tab does not take over the driver: the test must find the new handle and switch to it explicitly.

A stand-in: windows and handles

The model below keeps a list of windows and a "current" pointer, with window_handles, switch_to.window, close and new_window. A tiny rule is enforced: after closing the current window, using the driver fails until you switch, exactly as in a real session.

JS Window handles and switching

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The sequence to remember: read handles before the action, act, find the difference, switch, work, close, and switch back.

A stand-in: frames and an alert

The second model represents the page as a tree of frames. Locating an element only looks in the current frame, and default_content and parent_frame move the pointer. An alert blocks the page until it is accepted.

JS A frame tree and a blocking alert

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first search fails only because it was made from the wrong place. The same call succeeds after entering the frame. After the alert appeared, every command failed until it was accepted, the exact behaviour you will see in a real browser.

Habits for context switching

  • Always switch back. After finishing in a frame, return with default_content(). After a tab, return to the original handle.
  • Keep handles, not positions. Store main = driver.current_window_handle early; do not assume the new tab is the last in the list.
  • Wait for the context. Use alert_is_present, frame_to_be_available_and_switch_to_it and number_of_windows_to_be instead of sleeping.
  • Wrap switching in helpers or page objects (see The Page Object Model), so a test never mentions handles and frames directly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. An element is clearly visible on the page, but find_element raises NoSuchElementException. What is a likely cause?

    Locators search only the current context. An element inside an iframe is invisible to the main page until you switch into the frame.
  2. 2. A click opens a link in a new tab. Which statement is true?

    WebDriver never changes context on its own. Compare window_handles before and after the click to find the new handle, then switch.
  3. 3. What state is the session in right after driver.close() closes the current tab, while another tab is still open?

    close() ends only that window. The next command raises NoSuchWindowException until you switch_to.window(...) another handle. quit() is the call that ends the session.
  4. 4. Which call returns the script to the top-level document from any depth of nested frames?

    parent_frame() goes up one level; default_content() jumps directly to the top-level page.

Summary

  • The driver has one current context; locators only search inside it.
  • Alerts, confirms and prompts block the page: use EC.alert_is_present(), then accept(), dismiss() or send_keys(). HTML modals are normal elements.
  • Enter an iframe with switch_to.frame (an element or id is better than an index), step out with parent_frame(), and return to the page with default_content().
  • Windows and tabs have handles: record them before the action, find the new one by set difference, switch, and switch back after close().
  • quit() ends the whole session; close() closes one window and leaves the context undefined.

Next, learn how to move files in and out of the browser in File Uploads, Downloads and Screenshots.