Selenium C# Tutorial: Working with the Alert Box element
Updated: Mar 5
In this article, I will review the Alert Box element and the available options that selenium provides to handle it.
An Alert Box is a unique element that we cannot simply "Inspect" HTML code. Therefore all locators that we used until now (e.g., CSS, ID, Class, etc.) will not be available for use to use.
Selenium provides a specific namespace and classes that we can use to handle this technical limitation. To do it, add the "OpenQA.Selenium.Support.UI;" to your project. This will allow us to use the Ialert instance to perform all the operations we need on Alert boxes.
HTML:
<!DOCTYPE html><html><body> <h1>Demo: alert()</h1> <script> alert("This is alert box!"); // display string message
</script></body></html>
Alert Box:

class Program
{
static IAlert alert;
static void Main(string[] args)
{
IWebDriver firefoxDriver = new FirefoxDriver();
Backlog.TestPreperationGeneralSites(firefoxDriver, "file:///C:/Users/home-pc3/Downloads/new%201.html");
alert = firefoxDriver.SwitchTo().Alert();
//Print alert text to the console
Console.WriteLine(alert.Text);
//Approve the Alert
alert.Accept();
//Thread.Sleep(3000);
}