How to Handle Alerts/Popups in Selenium WebDriver – Selenium Tutorial #16

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated June 23, 2024

This tutorial provides efficient methods to handle alerts/popups in Selenium WebDriver for Windows and web-based applications.

In the previous tutorial, we focused on different types of waits provided by the WebDriver. We also discussed various types of navigation options available in WebDriver.

Moving ahead in the Selenium WebDriver Tutorials, we will discuss the different types of alerts available while testing web applications and their handling strategies.

Managing Alerts and Popups in Selenium WebDriver

Handling alerts popups in selenium

There are two types of alerts that we will focus on majorly:

  1. Windows-based alert pop-ups
  2. Web-based alert pop-ups

As we know handling Windows-based pop-ups is beyond WebDriver’s capabilities, thus we would exercise some third-party utilities to handle window pop-ups.

Handling pop-ups is one of the most challenging pieces of work to automate while testing web applications. The diversity of pop-up complexes makes the situation even more challenging.

What is an Alert box/Pop-up box/ confirmation Box/ Prompt/ Authentication Box?

It is nothing but a small box that appears on the display screen to give you some kind of information or to warn you about a potentially damaging operation or it may even ask you for the permissions for the operation.

Example: Let us consider a real-life example for a better understanding; Let us assume we uploaded a photograph on any of these popular social networking sites. Later on, I wish to delete the uploaded photograph.

So to delete, I clicked on the delete button. As soon as I click on the delete button, the system warns me against my action, prompting – Do you want to delete the file? So now we have an option to either accept this alert or reject it.

Before we begin the session, let’s figure out our approach to accepting or rejecting alerts based on their types. To start, let’s discuss the web-based pop-ups.

Web-Based Popups

web-based pop-ups

Let us see how we handle them using WebDriver.

Handling web-based pop-up box

WebDriver offers users with a very efficient way to handle these pop-ups using the Alert interface.

There are four methods that we will use along with the Alert interface.

  1. void dismiss(): The dismiss() method clicks on the “Cancel” button as soon as the pop-up window appears.
  2. void accept(): The accept() method clicks on the “OK” button as soon as the pop-up window appears.
  3. String getText(): The getText() method returns the text displayed on the alert box.
  4. void sendKeys(String stringToSend): The sendKeys() method enters the specified string pattern into the alert box.

Let us move ahead and look at the actual implementation.

Explanation of Application under Test

We have designed a web page in a way to includes a few fundamental types of web elements. This is the same application we introduced while discussing the Select class earlier in this series.

  • Hyperlink: The two hyperlinks namely “Google” and “abodeQA” have been provided that re-direct the user to “http://www.google.com/” and “http://www.abodeqa.com/” respectively, on the click event.
  • Dropdown: The three hyperlinks have been created for selecting colors, fruits, and animals with a value set to default.
  • Button: A “try it” button shows up the pop-up box having OK and Cancel buttons upon clicking the event.

(Click on image to view enlarged)

Application under Test

Subsequent is the HTML code used to create the above-mentioned webpage:

<!DOCTYPE html></pre>
<html>
<head><title> Testing Select Class </title>
<body>
<div id="header">
<ul id="linkTabs">
<li>
<a href="https://www.google.com/">Google</a>
</li>
<li>
<a href="http://abodeqa.wordpress.com/">abodeQA</a>
</li>
</ul>
</div>
<div class="header_spacer"></div>
<div id="container">
<div id="content" style="padding-left: 185px;">
<table id="selectTable">
<tbody>
<tr>
<td>
<div>
<select id="SelectID_One">
<option value="redvalue">Red</option>
<option value="greenvalue">Green</option>
<option value="yellowvalue">Yellow</option>
<option value="greyvalue">Grey</option>
</select>
</div>
</td>
<td>
<div>
<select id="SelectID_Two">
<option value="applevalue">Apple</option>
<option value="orangevalue">Orange</option>
<option value="mangovalue">Mango</option>
<option value="limevalue">Lime</option>
</select>
</div>
</td>
<td>
<div>
<select id="SelectID_Three">
<option value="selectValue">Select</option>
<option value="elephantvalue">Elephant</option>
<option value="mousevalue">Mouse</option>
<option value="dogvalue">Dog</option>
</select>
</div>
</td>
</tr>
<tr>
<td>
 
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a confirm box.</p>
<button onclick="myFunction()">Try it</button>
 
<script>
function myFunction()
{
confirm("Press a button!");
}
</script>
</body>
</html>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

Scenario to be automated

  1. Launch the web browser and open the webpage
  2. Click on the “Try it” button
  3. Accept the alert
  4. Click on the “Try it” button again
  5. Reject the alert

WebDriver Code using Select Class

Please take note that for script creation, we will use the “Learning_Selenium” project created in the former tutorial.

Step #1: Create a new Java class named as “DemoWebAlert” under the “Learning_Selenium” project.
Step #2: Copy and paste the below code in the “DemoWebAlert.java” class.

Below is the test script that is equivalent to the above-mentioned scenario.

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
 
/**
* class description
*/
 
public class DemoWebAlert {
                WebDriver driver;
                /**
                * Constructor
                */
                public DemoWebAlert() {                            
                }
 
                /**
                * Set up browser settings and open the application
                */
 
                @Before
                public void setUp() {
                                driver=new FirefoxDriver();
                                // Opened the application
                                driver.get("file:///F:/Work/Selenium/Testing-Presentation/DemoWebPopup.htm");
                                driver.manage().window().maximize();
                }
 
                /**
                * Test to check Select functionality
                * @throws InterruptedException
                */
 
                @Test
                public void testWebAlert() throws InterruptedException {                          
                                // clicking on try it button
                                driver.findElement(By.xpath("//button[contains(text(),'Try it')]")).click();
                               Thread.sleep(5000);
 
                                // accepting javascript alert
                                Alert alert = driver.switchTo().alert();
                                alert.accept();
 
                                // clicking on try it button
                                driver.findElement(By.xpath("//button[contains(text(),'Try it')]")).click();
                                Thread.sleep(5000);
 
                                // accepting javascript alert
                                driver.switchTo().alert().dismiss();
 
                                // clicking on try it button
                                driver.findElement(By.xpath("//button[contains(text(),'Try it')]")).click();
                                Thread.sleep(5000);
 
                                // accepting javascript alert
                                System.out.println(driver.switchTo().alert().getText());
                                driver.switchTo().alert().accept();
                }
 
                /**
                * Tear down the setup after test completes
                */
 
                @After
                public void tearDown() {             
                    driver.quit();
                }
}

Code Walk-through

Import Statements

Import org.openqa.selenium.Alert – Import this package prior to the script creation. The package references to the Alert class which is required to handle the web-based alerts in WebDriver.

Object Creation for Alert class
Alert alert = driver.switchTo().alert();

We create a reference variable for Alert class and references it to the alert.

Switch to Alert
Driver.switchTo().alert();
The above command is used to switch the control to the recently generated pop-up window.

Accept the Alert
alert.accept();
The above command accepts the alert, thereby clicking on the Ok button.

Reject the Alert
alert.dismiss();
The above command closes the alert, thereby clicking on the Cancel button and hence the operation should not proceed.

Window Based Pop-Ups

Window Based Pop-Ups

At times while automating, we get some scenarios where we need to handle pop-ups generated by Windows like a print pop-up or a browsing window while uploading a file.

Also read =>> How to handle file upload in Selenium

Handling these pop-ups has always been a little tricky as we know Selenium is an automation testing tool that supports only web application testing, that means it doesn’t support Windows-based applications and Window alert is one of them. However, some third-party intervention is necessary to overcome this problem, as Selenium alone can’t help the situation.

There are several third-party tools available for handling Window-based pop-ups along with the selenium.

So now let’s handle a Window-based pop-up using Robot class.

Robot class is a Java-based utility that emulates the keyboard and mouse actions. Before moving ahead, let us take a moment to have a look at the application under test (AUT).

Explanation of Application under Test

As an application under test, we will use “gmail.com”. I believe the application requires no more introductions.

Scenario to be automated

  1. Launch the web browser and open the application – “gmail.com”
  2. Enter a valid username and password
  3. Click on the sign in button
  4. Click on the compose button
  5. Click on the attach icon
  6. Select the files to be uploaded with the window-based pop-up.

WebDriver Code using Robot Class

Please note that for script creation, we will use the “Learning_Selenium” project created in the former tutorial.

Step #1: Create a new Java class named as “DemoWindowAlert” under the “Learning_Selenium” project.
Step #2: Copy and paste the below code in the “DemoWindowAlert.java” class.

Below is the test script that is equivalent to the above-mentioned scenario.

import java.awt.Robot;</pre>
import java.awt.event.KeyEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
 
public class DemoWindowAlert {
WebDriver driver;
@Before
 
public void setUp()
{
driver=new FirefoxDriver();
driver.get("https://gmail.com");
driver.manage().window().maximize();
}
 
@Test
public void testWindowAlert() throws Exception{
 
// enter a valid email address
driver.findElement(By.id("Email")).sendKeys("TestSelenium1607@gmail.com");
 
// enter a valid password
driver.findElement(By.id("Passwd")).sendKeys("TestSelenium");
 
// click on sign in button
driver.findElement(By.id("signIn")).click();
Thread.sleep(30000);
 
// click on compose button
driver.findElement(By.xpath("//div[@class='z0']//div[contains(text(),'COMPOSE')]")).click();
 
// click on attach files icon
driver.findElement(By.xpath("//div[contains(@command,'Files')]//div[contains(@class,'aaA')]")).click();
 
// creating instance of Robot class (A java based utility)
Robot rb =new Robot();
 
// pressing keys with the help of keyPress and keyRelease events
rb.keyPress(KeyEvent.VK_D);
rb.keyRelease(KeyEvent.VK_D);
Thread.sleep(2000);
 
rb.keyPress(KeyEvent.VK_SHIFT);
rb.keyPress(KeyEvent.VK_SEMICOLON);
rb.keyRelease(KeyEvent.VK_SEMICOLON);
rb.keyRelease(KeyEvent.VK_SHIFT);
 
rb.keyPress(KeyEvent.VK_BACK_SLASH);
rb.keyRelease(KeyEvent.VK_BACK_SLASH);
Thread.sleep(2000);
 
rb.keyPress(KeyEvent.VK_P);
rb.keyRelease(KeyEvent.VK_P);
 
rb.keyPress(KeyEvent.VK_I);
rb.keyRelease(KeyEvent.VK_I);
 
rb.keyPress(KeyEvent.VK_C);
rb.keyRelease(KeyEvent.VK_C);
Thread.sleep(2000);
 
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(2000);
}
 
@After
public void tearDown()
{
driver.quit();
}
}

Code Walk-through

Import Statements

import java.awt.Robot – Import this package prior to the script creation. The package references to the Robot class in Java which is required simulate keyboard and mouse events.

import java.awt.event.KeyEvent – The package allows the user to use keyPress and keyRelease events of a keyboard.

Object Creation for Robot class
Robot rb =new Robot();
We create a reference variable for Robot class and instantiate it.

KeyPress and KeyRelease Events
rb.keyPress(KeyEvent.VK_D);
rb.keyRelease(KeyEvent.VK_D);

The keyPress and keyRelease methods simulate the user pressing and releasing a certain key on the keyboard respectively.

Conclusion

In this tutorial, we tried to make you acquainted with the WebDriver’s Alert class that is used to handle web-based pop ups. We also briefed you about the Robot class that can populate the value in the Window-based alert with the help of keyPress and keyRelease events.

Article summary:

  • Alerts are small boxes on the screen that provide information or warn about potentially harmful operations or ask for permissions.
  • There are popularly two types of alerts
    • Windows-based alert pop-ups
    • Web-based alert pop ups
  • Prior to the actual scripting, we need to import a package to create a WebDriver script for handling a drop-down and making the Select class accessible.
  • Web driver offers users with a very efficient way to handle these pop-ups using the Alert interface.
  • void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop-up window appears.
  • void accept() – The accept() method clicks on the “OK” button as soon as the pop-up window appears.
  • String getText() – The getText() method returns the text displayed on the alert box.
  • void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
  • Handling window-based pop-ups has always been a little tricky as we know Selenium is an automation testing tool that supports only web application testing, which means, it doesn’t support Windows-based applications and window alert is one of them.
  • Robot class is a Java-based utility that emulates keyboard and mouse actions and can effectively handle window-based pop-ups with the help of keyboard events.
  • The keyPress and keyRelease methods simulate the user pressing and releasing a certain key on the keyboard respectively.

Next Tutorial #17: In the upcoming tutorial, we will discuss the various other commonly used WebDriver commands. We would shed light on topics like exception handling and iframe handling. We would also discuss about the get commands provided in WebDriver.

We would explain these topics with quick examples to make them understandable for the readers to exercise these concepts in their day to day scripting.

Note for the Readers: Till then, stay tuned and automate the web pages, having the web-based and window-based pop-ups using WebDriver utility – “Alert class” and Java utility – “Robot Class”.

Feel free to post any questions or comments about this tutorial or any previous ones in the comments section.

Was this helpful?

Thanks for your feedback!

Recommended Reading

51 thoughts on “How to Handle Alerts/Popups in Selenium WebDriver – Selenium Tutorial #16”

  1. I’m Unable to switch web based window. please find the below screen. i have tried multiple syntax but its not focusing on child window. its not having minimize and maximize symbols in the window.

    Reply
  2. A selenium developer handles Multiple windows/ popups under a single WebDriver. While trying to close a single popups windows.

    The developer find that the code block terminates all browser windows, which mistake the developer might be doing , that cause the issues and how can this issues be resolved?

    Reply
  3. when i used :

    val alert = browser.webDriver.switchTo().alert();
    println(“####################################” + alert.getText)
    alert.accept()

    its not working for me, I am using play framework, I already import org.openqa.selenium.Alert, but still not working. can any one help me?

    Reply
  4. Hi i am currently doing Automation and i have same Pop up is coming and i follow the exact the same code the one you using it here. But i got this error “unknown error: cannot determine loading status
    from unexpected alert open”. Any idea why i got this error. Thanks

    Reply
  5. How to handle a random popup? Because of this my tests are failing sometimes.The website was developed by other company, we are only (developing and testing) one frame(jobs column) of that website.This popup comes randomly from the other company for (business activities) which causes failure of my testcases.

    Reply
  6. Hello sir,

    My programme is stopping after clicking on popup window it is not able to move further , if you help me in this regard it would be appreciate

    package MNeConnect;
    import java.util.*;
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.remote.server.handler.GetWindowSize;
    import com.sun.jna.platform.unix.X11.Window;
    public class MNeConnect {
    public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub
    WebDriver driver = new FirefoxDriver();
    // Wait For Page To Load
    // Put a Implicit wait, this means that any search for elements on the page

    // Navigate to URL
    driver.get(“https://uat.mneconnect.com/PreProdMNeConnectAdmin/MNEHome.aspx”);
    // Maximize the window.
    driver.manage().window().maximize();
    // Enter UserName
    driver.findElement(By.id(“txtLogin”)).sendKeys(“bangalore”);
    // Enter Password
    driver.findElement(By.id(“txtPwd”)).sendKeys(“Password@12”);
    // Wait For Page To Load
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    // Click on ‘Sign In’ button
    driver.findElement(By.name(“buttonlogin”)).click();
    //Click on Compose Mail.
    driver.findElement(By.id(“lnkProviderAdmin”)).click();
    driver.findElement(By.linkText(“EDI Transactions”)).click();
    driver.findElement(By.id(“832”)).click();
    driver.findElement(By.linkText(“Primary”)).click();
    String mainwindowid=driver.getWindowHandle();
    System.out.println(“Main WIndow ID id”+mainwindowid);
    driver.findElement(By.cssSelector(“a[title=\”Select Patient\”]”)).click();
    Set windowId = driver.getWindowHandles();
    System.out.println(windowId.size());
    Iterator iterator=windowId.iterator();
    String popupWindow;
    while(iterator.hasNext())
    {
    popupWindow=iterator.next().toString();

    if(!popupWindow.equals((mainwindowid)))
    {
    driver.switchTo().window(popupWindow);
    driver.findElement(By.id(“btnSearch”)).click();
    }
    }

    }

    }

    Reply
  7. Getting the error ” unknown error: cannot determine loading status from unexpected alert open ” when dealing with pop ups in chrome browser.Please help me to resolve this issue

    Reply
  8. The use of Thread.sleep() in these examples shows that you do not know what you are doing and should not be writing any automation tests.

    For shame.

    Reply
  9. Hey Thanq so much,l was stuck from 2 days finding solution for the windows based pop ups . Finally Robot Class found me a way.. 🙂

    Reply
  10. Hi Sruthi,

    This was nice article, i tried to execute the code for window based popups which is on gmail compose mail scenario. As per the above code using robot class it worked till opening he popup but after that my was stopped and it is not performing any actions.

    Could you please let me know whether we need to use any specific server versions or anything needed to run the script smoothly on the gmail popup.

    Waiting for your reply.

    Thanks,
    Murthy K

    Reply
  11. excellent! i spent hours on google reading about getting window handles and switching to another window. this is new info for a situation i have never encountered before- thanks!

    Reply
  12. Hi,
    Please explain how will this Scenario work: I click on a Edit link or button pop up modal box displays with dropdown to select from and another field to enter data to enter in and then add data into another field to enter data then click on Submit. Please create tutorial for that.

    Reply
  13. How to handle pop-up which comes when opening flipkart site…”Are you on the App yet ?”, any help will be appreciated.

    Thanks
    Diljeet

    Reply
  14. For those having issues with the above where nothing happens after the pop-up is displayed (due to a connection error): Try either removing the thread.sleep line or reducing the value.

    Reply
  15. Hi sir ,i have doubt in this code.
    package sele_build;

    import java.util.Iterator;
    import java.util.Set;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class Handle_popupNAlert
    {
    public static void main(String[] args ) throws InterruptedException
    {
    System.setProperty(“webdriver.chrome.driver”, “D:\\selenium\\drivers\\chromedriver.exe”);

    WebDriver driver= new ChromeDriver();
    driver.get(“http://www.rediff.com/”);
    WebElement sign = driver.findElement(By.xpath(“//html/body/div[3]/div[3]/span[4]/span/a”));
    sign.click();

    Set windowId = driver.getWindowHandles(); // get window id of current window
    Iterator itererator = windowId.iterator();

    String mainWinID = itererator.next();
    String newAdwinID = itererator.next();

    driver.switchTo().window(newAdwinID);
    System.out.println(driver.getTitle());
    Thread.sleep(3000);
    driver.close();

    driver.switchTo().window(mainWinID);
    System.out.println(driver.getTitle());
    Thread.sleep(2000);

    WebElement email_id= driver.findElement(By.xpath(“//*[@id=’c_uname’]”));
    email_id.sendKeys(“hi”);
    Thread.sleep(5000);

    driver.close();
    driver.quit();
    }
    }
    can u please check code for

    Reply
  16. Hi,

    This post is really helped in how to handle the window popups. But driver.accept(), driver.dismiss() only work for javascript pops not for jquery popups.
    Can any one tell me how to handle query popups.

    Reply
  17. hi shruthi,it is a great tutorial.thanque.
    i cannot see keyPress methods after clicking robot object . (dot)in eclipse.I imported java.awt.*.What might be the problem,please tell me.

    Reply
  18. Hi ,

    i have a pop up generated stating incident id INC00000001234 is generated and a OK button,

    i need to copy that id and click on OK and then use that id.
    Location of that popup window is not stable. it changes everytime.

    Reply
  19. Hi Jino,
    please find the below script.
    Public class Menu
    {
    public static void main(String[]args)
    {
    WebDriver driver = new FirefoxDriver();
    driver.get(“url”);
    WebElement element = driver.findElemnt(By.id(“element of the menu”));
    Actions action = new Actions(driver);
    action.moveToElemnt(element).perform();
    driver.findElemnt(By.id(“location of the hidden drop down menu”)).click();
    }
    }

    Reply
  20. Can we Enter text into alert boxes?
    you mentioned in summary points that we can enter data using sendKeys() method is it possible?

    Reply
  21. I am unable to get the Robot class code to work on a Mac with Chrome. The Mac file browser comes up but doesn’t get focus (Cancel button isn’t active, etc.), the system beeps with the Robot keypress attempts, and then the file browser gets focus.

    I tried adding some Thred.sleep() delays, but no good. Is there a driver.switchTo() command I need to insert?

    Reply
  22. SHOWING ERRORS,plz help on this
    @Test
    public void h() {
    WebElement element = driver.findElement(By.xpath(“/html/body/div[1]/div/div[6]/div[2]/div/div[1]/div/ul/li[1]/a”));
    Actions action = new Actions(element);
    action.moveToElement(element).build().perform();
    element.findElement(By.xpath(“/html/body/div[1]/div/div[6]/div[2]/div/div[1]/div/ul/li[1]/ul/li[2]/a”)).click();
    Thread.sleep(2000);
    }

    Reply
  23. Hi,

    If i copy the html code in notepad it takes the left numbers as well. Are there any way to copy the code that is here for practice?

    Reply
  24. Vijay Please tell me that How to handle sub child windows(more than 3) using Selenium Web Driver with Java?
    My project is like Parent->Child->Child1->Child2->Child3->Child->Parent.

    Reply
  25. Thanks it was really useful to know about Robot class.

    It was interesting to see this kind of automation. How to select the check box which comes on the alert box ?

    Example :- There is a checkbox comes with the message on alert box . ” do you want it to not generate further checkboxes”

    Reply
  26. Hi!
    I have a problem in which when there is a javascript alert window and a user accept it, then the next time the c# application tries to access the web browser it fails with a message “found text( alert: ‘the message on the alert window’) disappeared before…” but when you handle the alert using the c# application next time you don’t get the error. It seems like if there is a pop up immediately the selenium web driver gets it and when a user accepts it the selenium driver gets exceptions how can we handle that cause i tried using try catch but it didn’t work. Thanks for any help.

    Reply
  27. Below please find a class that can be used for the same scenario in C#.

    Source : http://www.codeproject.com/Articles/28064/Global-Mouse-and-Keyboard-Library

    using System;
    using System.Drawing;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;

    namespace Utils
    {
    ///
    /// Handle Keyboard and Mouse events
    ///
    public static class Robot
    {
    private static class Native
    {
    [DllImport(“user32.dll”)]
    internal static extern int ShowCursor(bool show);

    [DllImport(“user32.dll”)]
    internal static extern void mouse_event(int flags, int dX, int dY, int buttons, int extraInfo);

    [DllImport(“user32.dll”)]
    internal static extern void keybd_event(byte key, byte scan, int flags, int extraInfo);

    internal const int MOUSEEVENTF_MOVE = 0x1;
    internal const int MOUSEEVENTF_LEFTDOWN = 0x2;
    internal const int MOUSEEVENTF_LEFTUP = 0x4;
    internal const int MOUSEEVENTF_RIGHTDOWN = 0x8;
    internal const int MOUSEEVENTF_RIGHTUP = 0x10;
    internal const int MOUSEEVENTF_MIDDLEDOWN = 0x20;
    internal const int MOUSEEVENTF_MIDDLEUP = 0x40;
    internal const int MOUSEEVENTF_WHEEL = 0x800;
    internal const int MOUSEEVENTF_ABSOLUTE = 0x8000;

    internal const int KEYEVENTF_EXTENDEDKEY = 0x1;
    internal const int KEYEVENTF_KEYUP = 0x2;
    }

    ///
    /// Handle Mouse events
    ///
    public static class Mouse
    {
    private enum MouseButton
    {
    Left = 0x2,
    Right = 0x8,
    Middle = 0x20
    }

    #region Properties

    ///
    /// Gets or sets a structure that represents both X and Y mouse coordinates
    ///
    public static Point Position
    {
    get
    {
    return new Point(Cursor.Position.X, Cursor.Position.Y);
    }
    set
    {
    Cursor.Position = value;
    }
    }

    ///
    /// Gets or sets only the mouse’s x coordinate
    ///
    public static int X
    {
    get
    {
    return Cursor.Position.X;
    }
    set
    {
    Cursor.Position = new Point(value, Y);
    }
    }

    ///
    /// Gets or sets only the mouse’s y coordinate
    ///
    public static int Y
    {
    get
    {
    return Cursor.Position.Y;
    }
    set
    {
    Cursor.Position = new Point(X, value);
    }
    }

    #endregion

    #region Methods

    ///
    /// Press a mouse button down
    ///
    ///
    private static void MouseDown(MouseButton button)
    {
    Native.mouse_event(((int)button), 0, 0, 0, 0);
    }

    ///
    /// Press a mouse button down
    ///
    ///
    public static void MouseDown(MouseButtons button)
    {
    switch (button)
    {
    case MouseButtons.Left:
    MouseDown(MouseButton.Left);
    break;
    case MouseButtons.Middle:
    MouseDown(MouseButton.Middle);
    break;
    case MouseButtons.Right:
    MouseDown(MouseButton.Right);
    break;
    }
    }

    ///
    /// Let a mouse button up
    ///
    ///
    private static void MouseUp(MouseButton button)
    {
    Native.mouse_event(((int)button) * 2, 0, 0, 0, 0);
    }

    ///
    /// Let a mouse button up
    ///
    ///
    public static void MouseUp(MouseButtons button)
    {
    switch (button)
    {
    case MouseButtons.Left:
    MouseUp(MouseButton.Left);
    break;
    case MouseButtons.Middle:
    MouseUp(MouseButton.Middle);
    break;
    case MouseButtons.Right:
    MouseUp(MouseButton.Right);
    break;
    }
    }

    ///
    /// Click a mouse button (down then up)
    ///
    ///
    private static void Click(MouseButton button)
    {
    MouseDown(button);
    MouseUp(button);
    }

    ///
    /// Click a mouse button (down then up)
    ///
    ///
    public static void Click(MouseButtons button)
    {
    switch (button)
    {
    case MouseButtons.Left:
    Click(MouseButton.Left);
    break;
    case MouseButtons.Middle:
    Click(MouseButton.Middle);
    break;
    case MouseButtons.Right:
    Click(MouseButton.Right);
    break;
    }
    }

    ///
    /// Double click a mouse button (down then up twice)
    ///
    ///
    private static void DoubleClick(MouseButton button)
    {
    Click(button);
    Click(button);
    }

    ///
    /// Double click a mouse button (down then up twice)
    ///
    ///
    public static void DoubleClick(MouseButtons button)
    {
    switch (button)
    {
    case MouseButtons.Left:
    DoubleClick(MouseButton.Left);
    break;
    case MouseButtons.Middle:
    DoubleClick(MouseButton.Middle);
    break;
    case MouseButtons.Right:
    DoubleClick(MouseButton.Right);
    break;
    }
    }

    ///
    /// Roll the mouse wheel. Delta of 120 wheels up once normally, -120 wheels down once normally
    ///
    ///
    public static void MouseWheel(int delta)
    {
    Native.mouse_event(Native.MOUSEEVENTF_WHEEL, 0, 0, delta, 0);
    }

    ///
    /// Show a hidden current on currently application
    ///
    public static void Show()
    {
    Native.ShowCursor(true);
    }

    ///
    /// Hide mouse cursor only on current application’s forms
    ///
    public static void Hide()
    {
    Native.ShowCursor(false);
    }

    #endregion

    }

    ///
    /// Handle Keyboard events
    ///
    public static class Keyboard
    {
    ///
    /// Handle Type
    ///
    ///
    public static void Type(string text)
    {
    //TODO: Make {SpecialChar} logic/
    var letters = text.ToCharArray();
    foreach (var letter in letters)
    {
    KeyPress(letter);
    }
    }

    ///
    /// Handle KeyDown
    ///
    ///
    public static void KeyDown(Keys key)
    {
    Native.keybd_event(ParseKey(key), 0, 0, 0);
    }

    ///
    /// Handle KeyDown
    ///
    ///
    public static void KeyDown(string key)
    {
    KeyDown(Key(key));
    }

    ///
    /// Handle KeyDown
    ///
    ///
    public static void KeyDown(char key)
    {
    KeyDown(key.ToString());
    }

    ///
    /// Handle KeyUp
    ///
    ///
    public static void KeyUp(Keys key)
    {
    Native.keybd_event(ParseKey(key), 0, Native.KEYEVENTF_KEYUP, 0);
    }

    ///
    /// Handle KeyUp
    ///
    ///
    public static void KeyUp(string key)
    {
    KeyUp(Key(key));
    }

    ///
    /// Handle KeyUp
    ///
    ///
    public static void KeyUp(char key)
    {
    KeyUp(key.ToString());
    }

    ///
    /// Handle KeyPress
    ///
    ///
    public static void KeyPress(Keys key)
    {
    KeyDown(key);
    KeyUp(key);
    }

    ///
    /// Handle KeyPress
    ///
    ///
    public static void KeyPress(string key)
    {
    if (key != key.ToUpper())
    {
    KeyPress(Key(key));
    }
    else
    {
    KeyDown(Keys.Shift);
    KeyPress(Key(key));
    KeyUp(Keys.Shift);
    }
    }

    ///
    /// Handle KeyPress
    ///
    ///
    public static void KeyPress(char key)
    {
    KeyPress(key.ToString());
    }

    private static byte ParseKey(Keys key)
    {
    switch (key)
    {
    case Keys.Alt:
    return (byte)18;
    case Keys.Control:
    return (byte)17;
    case Keys.Shift:
    return (byte)16;
    default:
    return (byte)key;
    }
    }

    private static Keys Key(string key)
    {
    return (Keys)Enum.Parse(typeof(Keys), key, true);
    }
    }
    }
    }

    Reply
  28. This is a great article. top information on how to work with Selenium. can I offer you publishing this article in QATestingTools.com ?

    Reply
  29. Actually I want the copy the partial text from the popup window and the text will be the input in the other screen.

    How i can able to handle it using selenium webdriver

    Reply
  30. Hi,

    When i try to execute the above code, it worked till opening a popup window later with robot class declaration it is not performing any actions in the window popup.

    Do we need to do any other configurations for this.

    Thanks,
    Bhaskar

    Reply
  31. Hi,

    In my project we are using PhantomJS headless browser. Using Alert interface we are not able to handle popup’s in this browser. I heard using Javascript, we can handle popup’s in phantomJS. Could you provide Javascript code for handling popup’s in phantomJS, If you know.

    Reply
  32. @Rohit

    The methods like dismiss(), accept etc surely works for Web Based pop ups.
    But to tackle Windows based popups, you need to approach differently. Robot Class explained in this tutorial is one of the many available options.

    Reply

Leave a Comment