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 orDismiss()to cancel. - Prompt: call
SendKeys("test input"), thenAccept()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.
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:
#1 Best Overall
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.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11When 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:
Rank #3
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:
Rank #4
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.
Recommended Free Tools
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.
Best Value
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 callingText,Accept(),Dismiss(), orSendKeys().NoSuchWindowExceptionafter 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 currentWindowHandlescollection.- 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.
Singlethrows 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.
NewWindowis 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:
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →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.
Quick Recap
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.




