This is our first post in Learn Selenium Series.  Today, we are going to discuss about handling Windows Alerts in Selenium.  Selenium is a web application automation tool.  Hence, handling all kinds of Alerts like Confirmation Alert, Prompt Alert are straight forwarded Alerts.  Selenium should support handling these alerts and it does also.

How to handle Windows Alerts in Selenium
The biggest question stands in front of us is – How can we handle Windows Alerts in Selenium?  Without handling Windows Alerts, it is impossible to get involved in real projects.  There are some third party tools used along with Selenium.  One such tool is AutoIT.  It uses Scripting language to handle Windows Alerts.  Selenium developers can use this tool as it is a free Software.

Is AutoIT the only solution?
Though AutoIT helps to handle Windows Alerts, there are some prerequisites also.  The very primary prerequisite is the Automation Testers (Or Selenium Developers) should know the scripting language also along with their OOP language.  This could be a major hurdle for them.  Is there anyother solution for this?  Do Java, the evergreen language has any solution for this internally?

Robot Class in Java:
There is a predefined Java Class called Robot.  This is present in java.awt package.  Java Doc says that Robot class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations. There is one more class called KeyEvent.  This is present in java.awt.event package.  An event which indicates that a keystroke occurred in a component.  We can make use of these two built in classes in Java.

I am providing you the code snippet which uses KeyEvent and Robot Class below.  This snippet handles Windows Alerts in Selenium.  I am focusing for Print Windows popup here using these classes.  Similarly, we can handle all kinds of Windows Alerts in Selenium.

// Setting up gecko driver
System.setProperty(“webdriver.gecko.driver”,”E://geckodriver.exe”);
WebDriver webDriver = new FirefoxDriver();
// get method for opening a website
webDriver.get(“https://payilagam.com”);
// First Approach for pressing Ctrl + P Using Actions Class (Commented here)
//Actions actions = new Actions(webDriver);
// actions.sendKeys(Keys.CONTROL).clickAndHold().sendKeys(“P”).click();

// Second Approach for pressing Ctrl + P
Robot robot =new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_P);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_P);
// The below method clicks on Ok Button in the Print Windows Alert
robot.keyPress(KeyEvent.VK_ENTER);

Hope you enjoyed this post.  Lets meet in another post in Learn Selenium Series later.