Enroll in Selenium Training

Alert is a pop up window that comes up on screen. There are many user actions that can result in an alert on screen. For e.g. user clicked on a button that displayed a message or may be when you entered a form, HTML page asked you for some extra information. So in this chapter we will learn How to Handle Different types of Alert And Popup Box in Selenium CSharp.

Test Page for alerts: http://toolsqa.com/handling-alerts-using-selenium-webdriver

Alerts are different from regular windows. The main difference is that alerts are blocking in nature. They will not allow any action on the underlying webpage if they are present. So if an alert is present on the webpage and you try to access any of the element in the underlying page you will get following exception:

AlertWindowPresent

UnhandledAlertException: Modal dialog present

To reproduce this exception you can use this code:

namespace ToolsQA.Selenium_Basics
{
    class Alerts
    {
        [Test]
        public void Test()
        {
			IWebDriver driver = new FirefoxDriver();
			driver.Url = "https://toolsqa.com/handling-alerts-using-selenium-webdriver/";

			//This step produce an alert on screen
			driver.FindElement(By.XPath("//*[@id='content']/p[4]/button")).Click();

			//Once alert is present try to click on any button on the page
			driver.FindElement(By.XPath("//*[@id='content']/p[16]/button")).Click();
        }
    }
}

Handling Alerts using Selenium WebDriver

Selenium provides us with an interface called Alert (It is a Interface).

AlertWindowPresent

It is present in the OpenQA.Selenium.IAlert package. Alert interface gives us following methods to deal with the alert:

  • .Accept() To accept the alert
  • .Dismiss() To dismiss the alert
  • .Text To get the text of the alert
  • .SendKeys() To write some text to the alert

AlertWindowPresent

Let's use these to handle the above-mentioned types of alerts one by one.

Simple Alert

Simple alerts just have a OK button on them. They are mainly used to display some information to the user. The first alert on our test page is a simple alert. Following code will read the text from the Alert and then accept the alert. Important point to note is that we can switch from main window to an alert using the driver.SwitchTo().Alert().

Below is the usage of that also:

namespace ToolsQA.Selenium_Basics
{
    class SimpleAlerts
    {
        [Test]
        public void Test()
        {
			IWebDriver driver = new FirefoxDriver();
			driver.Url = "https://toolsqa.com/handling-alerts-using-selenium-webdriver/";
			driver.Manage().Window.Maximize();

			//This step produce an alert on screen
			driver.FindElement(By.XPath("//*[@id='content']/p[4]/button")).Click();

			// Switch the control of 'driver' to the Alert from main Window
			IAlert simpleAlert = driver.SwitchTo().Alert();
			
			// '.Text' is used to get the text from the Alert
			String alertText = simpleAlert.Text;
			Console.WriteLine("Alert text is " + alertText);
					
			// '.Accept()' is used to accept the alert '(click on the Ok button)'
			simpleAlert.Accept();
        }
    }
}

Confirmation Alert

This alert comes with an option to accept or dismiss the alert. To accept the alert you can use IAlert.Accept() and to dismiss you can use the IAlert.Dismiss().

Here is the code to dismiss a confirmation alert.

namespace ToolsQA.Selenium_Basics
{
    class ConfirmationAlerts
    {
        [Test]
        public void Test()
        {
			IWebDriver driver = new FirefoxDriver();
			driver.Url = "https://toolsqa.com/handling-alerts-using-selenium-webdriver/";
			driver.Manage().Window.Maximize();

			//This step produce an alert on screen
			IWebElement element = driver.FindElement(By.XPath("//*[@id='content']/p[8]/button"));

			// 'IJavaScriptExecutor' is an interface which is used to run the 'JavaScript code' into the webdriver (Browser)
			((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click()", element);

			// Switch the control of 'driver' to the Alert from main window
			IAlert confirmationAlert = driver.SwitchTo().Alert();

			// Get the Text of Alert
			String alertText = confirmationAlert.Text;

			Console.WriteLine("Alert text is " + alertText);

			//'.Dismiss()' is used to cancel the alert '(click on the Cancel button)'
			confirmationAlert.Dismiss();
        }
    }
}

Prompt Alerts

In prompt alerts you get an option to add text to the alert box. This is specifically used when some input is required from the user. We will use the SendKeys() method to type something in the Prompt alert box.

Here is the code

namespace ToolsQA.Selenium_Basics
{
    class PromptAlerts
    {
        [Test]
        public void Test()
        {  IWebDriver driver = new FirefoxDriver();

			driver.Url = "https://toolsqa.com/handling-alerts-using-selenium-webdriver/";
			driver.Manage().Window.Maximize();

			//This step produce an alert on screen
			IWebElement element = driver.FindElement(By.XPath("//*[@id='content']/p[11]/button"));

			// 'IJavaScriptExecutor' is an 'interface' which is used to run the 'JavaScript code' into the webdriver (Browser)        
			((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click()", element);

			// Switch the control of 'driver' to the Alert from main window
			IAlert promptAlert = driver.SwitchTo().Alert();

			// Get the Text of Alert
			String alertText = promptAlert.Text;
			Console.WriteLine("Alert text is " + alertText);

			//'.SendKeys()' to enter the text in to the textbox of alert 
			promptAlert.SendKeys("Accepting the alert");

			Thread.Sleep(4000); //This sleep is not necessary, just for demonstration

			// '.Accept()' is used to accept the alert '(click on the Ok button)'
			promptAlert.Accept();
        }
    }
}

Note: Common Exception in this Alert Handling is NoAlertPresentException:

How to Handle Different types of Alert And Popup Box in Selenium CSharp

This is also an important point which people rather tend to miss

Alert

This popup is also handled by the same code of popup

IAlert simpleAlert = driver.SwitchTo().Alert();
String alertText = simpleAlert.Text;
Console.WriteLine("Alert text is " + alertText);
simpleAlert.Accept();

Where

simpleAlert.Accept(); = > Press the 'Leave Page' Button simpleAlert.Dismiss(); = > Press the 'Stay on Page' Button

That’s pretty much it on the Alerts that we have.

Happy Automation :-)(y)

Handle Dynamic WebTables with Selenium in CSharp
Handle Dynamic WebTables with Selenium in CSharp
Previous Article
How to Handle Multiple Browsers in Selenium CSharp
How to Handle Multiple Browsers in Selenium CSharp
Next Article

Similar Articles

Feedback