Skip to content

Instantly share code, notes, and snippets.

@bharathmuddada
Last active August 9, 2022 00:36
Show Gist options
  • Save bharathmuddada/acd8cc0e203603839d598a96b2da3dae to your computer and use it in GitHub Desktop.
Save bharathmuddada/acd8cc0e203603839d598a96b2da3dae to your computer and use it in GitHub Desktop.
C# Selenium Program to handle javascript alerts
public class SeleniumJSAlertSample {
public static void Main(string[] args)
{
new DriverManager().SetUpDriver(new ChromeConfig());
var driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/javascript_alerts");
driver.Manage().Window.Maximize();
var popup = driver.FindElement(By.XPath("//button[contains(text(),'Alert')]"));
popup.Click();
var alert = driver.SwitchTo().Alert();
Console.WriteLine(alert.Text);
alert.Dismiss();
Console.WriteLine(driver.FindElement(By.XPath("//p[@id='result']")).Text);
var confirm_popup = driver.FindElement(By.XPath("//button[contains(text(),'Confirm')]"));
confirm_popup.Click();
Console.WriteLine(alert.Text);
alert.Accept();
Console.WriteLine(driver.FindElement(By.XPath("//p[@id='result']")).Text);
var prompt = driver.FindElement(By.XPath("//button[contains(text(),'Prompt')]"));
prompt.Click();
Console.WriteLine(alert.Text);
alert.SendKeys("test");
alert.Accept();
Console.WriteLine(driver.FindElement(By.XPath("//p[@id='result']")).Text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment