Skip to content
All notes
36SeleniumAutomationSelenium

How do you handle alerts, pop-ups, and windows in Selenium?

1. Handling Alerts

JavaScript alerts can be accepted, dismissed, or text can be retrieved/entered.

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

# Wait for alert
wait = WebDriverWait(driver, 10)
alert = wait.until(EC.alert_is_present())

# Get alert text
alert_text = alert.text

# Accept alert (click OK)
alert.accept()

# Dismiss alert (click Cancel)
alert.dismiss()

# Enter text in prompt
alert.send_keys("Test input")
alert.accept()

2. Handling Multiple Windows/Tabs

# Get current window handle
main_window = driver.current_window_handle

# Get all window handles
all_windows = driver.window_handles

# Switch to new window
for window in all_windows:
    if window != main_window:
        driver.switch_to.window(window)
        # Perform actions in new window
        driver.close()  # Close new window

# Switch back to main window
driver.switch_to.window(main_window)

3. Handling iFrames

# Switch to iframe by index
driver.switch_to.frame(0)

# Switch to iframe by name or ID
driver.switch_to.frame("frameName")

# Switch to iframe by WebElement
iframe_element = driver.find_element(By.ID, "iframeId")
driver.switch_to.frame(iframe_element)

# Switch back to main content
driver.switch_to.default_content()

# Switch to parent frame
driver.switch_to.parent_frame()

4. Handling Pop-ups (Browser Notifications)

# Disable notifications in Chrome
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--disable-notifications")
driver = webdriver.Chrome(options=chrome_options)

Best Practices

  • Always wait for alerts before interacting
  • Store original window handle before opening new windows
  • Always switch back to default content after iframe operations
  • Close windows/tabs when done to avoid memory leaks