Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
Redmond desk6 min

How to Handle Alerts and Windows in Selenium with C#

Use Selenium’s IAlert API for JavaScript dialogs and window handles for tabs and windows. This C# guide shows safe waits, switching, cleanup, and common fixes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use driver.SwitchTo().Alert() for JavaScript alert, confirmation, and prompt dialogs. Use window handles with driver.SwitchTo().Window(handle) to work in a tab or window. In both cases, wait for the target to exist before interacting with it; after closing a child window, switch back to a handle that remains open.

Handle JavaScript alerts, confirmations, and prompts

JavaScript dialogs are not ordinary page elements. Selenium exposes them through IAlert, obtained from the driver’s target locator. Read the dialog text with Text, then accept or dismiss it according to the behavior under test. For a prompt, send text before accepting.

As an Amazon Associate I earn from qualifying purchases.

  • Alert: read the message if needed, then call Accept().
  • Confirmation: call Accept() to confirm or Dismiss() to cancel.
  • Prompt: call SendKeys("test input"), then Accept() to submit.
using OpenQA.Selenium;

// Run the page action that opens the JavaScript alert before this point.
IAlert alert = driver.SwitchTo().Alert();
string message = alert.Text;
alert.Accept();

// For a confirmation the test intends to cancel:
IAlert confirmation = driver.SwitchTo().Alert();
confirmation.Dismiss();

// For a prompt:
IAlert prompt = driver.SwitchTo().Alert();
prompt.SendKeys("test input");
prompt.Accept();

Each example assumes the relevant dialog is currently open. IAlert provides the text and the Accept(), Dismiss(), and SendKeys(string) operations. See the Selenium alerts guide and the .NET IAlert API reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Wait when the dialog appears asynchronously

If an action triggers a dialog asynchronously, do not immediately request the alert and assume it is ready. Use a condition wait for the project’s Selenium version. The .NET WebDriverWait supports waiting on a test condition; a wait can retry while no alert is present:

using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IAlert alert = wait.Until(d =>
{
    try
    {
        return d.SwitchTo().Alert();
    }
    catch (NoAlertPresentException)
    {
        return null;
    }
});

string message = alert.Text;
alert.Accept();

This example requires the Selenium.Support package and the System namespace for TimeSpan. Set the timeout to suit the application and test environment. The wait ends when an alert is found or times out; handle a timeout as a test failure or investigate why the expected dialog did not appear. See the .NET WebDriverWait API reference.

Switch to a tab or window opened by the application

WebDriver uses handles to identify browser tabs and windows. Save the current handle before triggering the action, wait for the new handle to appear, then switch to it. Do not rely on a fixed index in WindowHandles; identify the new handle by comparing it with the original.

using System;
using System.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

string original = driver.CurrentWindowHandle;
driver.FindElement(By.LinkText("Open new window")).Click();

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(d => d.WindowHandles.Count == 2);

string child = driver.WindowHandles.Single(handle => handle != original);
driver.SwitchTo().Window(child);

// Interact with the child page here.

 driver.Close();
driver.SwitchTo().Window(original);

Replace the link text with a locator that matches your application, and put the child-page assertions or interactions where indicated. This pattern expects exactly two open contexts after the click: the original and one child. Selenium’s windows and tabs guide uses the same save-wait-identify-switch sequence.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When there may be more than one existing tab

If other tabs can already be open, compare the handles present before the action with those present afterward instead of assuming there will be exactly two:

var before = driver.WindowHandles.ToHashSet();
driver.FindElement(By.LinkText("Open new window")).Click();

wait.Until(d => d.WindowHandles.Any(handle => !before.Contains(handle)));
string child = driver.WindowHandles.Single(handle => !before.Contains(handle));
driver.SwitchTo().Window(child);

If the action can open several contexts, select the intended one using an application-specific signal, such as its URL or title, and iterate over the new handles. Selenium’s guide recommends looping through handles when there are more than two windows or tabs; never assume a particular handle is at array index 1.

Create a tab or window directly in Selenium 4+

When the test—not the application—needs a fresh browser context, Selenium 4 and later provide NewWindow. The operation creates and focuses the new context, so no second switch is required:

driver.SwitchTo().NewWindow(WindowType.Tab);
// The newly created tab is now the active context.

For a separate window, pass WindowType.Window instead. This direct operation is documented for Selenium 4 and later; check the installed Selenium .NET version before using it. Consult the .NET ITargetLocator API reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Close a child context and return safely

driver.Close() closes the currently selected tab or window, not necessarily the whole browser session. After closing a child, explicitly switch to a handle that still exists before issuing more WebDriver commands. Selenium warns that remaining on the closed context can trigger a No Such Window Exception. If the original context may also have been closed, choose another handle from the current WindowHandles collection rather than switching to a stale one.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Complete C# example setup

The following console-app skeleton shows the necessary driver lifecycle and wait imports. Install the Selenium .NET WebDriver and Support packages, and configure a browser driver such as ChromeDriver for your environment. Replace the sample URL and locator with a page and control in your own test environment; a real target page must actually open the dialog or child context for the relevant branch to run.

using System;
using System.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;

class Program
{
    static void Main()
    {
        IWebDriver driver = new ChromeDriver();
        try
        {
            driver.Navigate().GoToUrl("https://example.com");

            // Example alert branch: replace with a page action that opens an alert.
            // driver.FindElement(By.Id("show-alert")).Click();
            // var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            // IAlert alert = wait.Until(d =>
            // {
            //     try { return d.SwitchTo().Alert(); }
            //     catch (NoAlertPresentException) { return null; }
            // });
            // Console.WriteLine(alert.Text);
            // alert.Accept();

            // Example child-window branch: replace locator with the application's link.
            // string original = driver.CurrentWindowHandle;
            // driver.FindElement(By.LinkText("Open new window")).Click();
            // var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            // wait.Until(d => d.WindowHandles.Count == 2);
            // string child = driver.WindowHandles.Single(h => h != original);
            // driver.SwitchTo().Window(child);
            // Console.WriteLine(driver.Title);
            // driver.Close();
            // driver.SwitchTo().Window(original);
        }
        finally
        {
            driver.Quit();
        }
    }
}

The branches are commented out because their locators and expected dialog behavior depend on the page under test; uncomment and adapt one branch at a time. Quit() ends the session and closes its remaining browser contexts, so call it during cleanup even when a test fails.

Troubleshoot common failures

  • NoAlertPresentException: the dialog has not appeared yet, the triggering action did not open one, or it was already handled. Verify the action and wait for the alert before calling Text, Accept(), Dismiss(), or SendKeys().
  • NoSuchWindowException after closing a tab: WebDriver is still targeting the closed context, or the handle you saved is no longer open. Switch to a handle in the current WindowHandles collection.
  • The new-window wait times out: confirm that the click succeeded and that the application is expected to open a separate tab or window. A page navigation in the same tab does not create another handle; inspect the current page and adjust the expected behavior.
  • Single throws because there are zero or multiple matches: the expected handle is not unique under the current assumptions. Snapshot the handles before the action, wait for a new one, and use an application-specific criterion if multiple contexts can appear.
  • Commands affect the wrong page: switching changes WebDriver’s active context. Explicitly switch to the intended handle before reading page state or locating elements.
  • NewWindow is unavailable: that API is documented for Selenium 4 and later. Check the installed Selenium .NET package version, or use the application-opened-window handle pattern when appropriate.

Or skip the browser setup

ScreenshotNeo is a screenshot API, not a Selenium replacement for interacting with JavaScript dialogs or managing browser contexts. For a rendered-page capture, one GET request returns an image or PDF:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

See the ScreenshotNeo API documentation. It accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Its MCP server lets AI agents use take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Try ScreenshotNeo free: 1,000 screenshots a month, no card required.

Sources and version note

The Selenium Project’s browser-interactions documentation reports a last-modified date of September 16, 2026. Match API usage to the Selenium .NET version installed in your project. See Browser interactions and the .NET IWebDriver API reference.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.