A2oz

How to Handle Windows-Based Popups in Selenium Using C#?

Published in Selenium Automation 2 mins read

You can handle Windows-based popups in Selenium using C# by switching the driver's focus to the popup window and then interacting with it as needed. Here's how:

1. Identify the Popup Window

  • Use the FindElement method: Locate the popup window using its unique identifier (e.g., title, class name, or ID).
  • Use the SwitchTo method: Switch the driver's focus to the newly identified popup window.

2. Interact with the Popup Window

  • Perform actions: Once you've switched to the popup window, you can interact with it using Selenium's commands, such as SendKeys, Click, or GetAttribute.
  • Handle specific actions: For example, if you need to click a "Save" button, use the Click method on the corresponding element.

3. Close the Popup Window

  • Use the Close method: After you've completed the necessary actions, close the popup window using the Close method.
  • Switch back to the main window: After closing the popup, switch back to the main window using the SwitchTo method and the DefaultContent property.

Example Code

// Assuming the popup window title is "My Popup"
IWebElement popupWindow = driver.FindElement(By.CssSelector("title[text='My Popup']"));

// Switch to the popup window
driver.SwitchTo().Window(popupWindow.GetAttribute("id"));

// Perform actions within the popup window
// ...

// Close the popup window
driver.Close();

// Switch back to the main window
driver.SwitchTo().DefaultContent();

Practical Insights

  • Handle multiple popups: If you encounter multiple popups, you can use the GetWindowsHandles method to retrieve a list of all open window handles. Then iterate through the list and switch to each window to handle it individually.
  • Wait for the popup to appear: Use explicit waits to ensure the popup window has fully loaded before attempting to interact with it.
  • Handle alerts: Use the Alert property to interact with JavaScript alerts that may appear within the popup window.

Related Articles