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

Efficient Ways to Handle Windows and Web-based Alerts/Popups in Selenium WebDriver:

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

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

Handling alerts popups in selenium

There are two types of alerts that we would be focusing on majorly:

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

As we know that 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 up is one of the most challenging pieces of work to automate while testing web applications. Owing to the diversity in types of pop ups complexes the situation even more.

What is 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 that we uploaded a photograph on any of these popular social networking sites. Later on, I wish to delete the uploaded photograph. So in order 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 really want to delete the file? So now we have an option to either accept this alert or reject it.

So ahead of the session, let’s see how do we reject or accept the alerts depending on their types. Starting with the web-based pop ups.

Web-Based Popups

webdriver alerts 1

Let us see how do we handle them using WebDriver.

Handling web-based pop-up box

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

There are the four methods that we would be using 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 include a few fundamental types of web elements. This is the same application we introduced while discussing Select class earlier in this series.

  • Hyperlink: The two hyperlinks namely “Google” and “abodeQA” have been provided that re-directs 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 colours, fruits and animals with a value set to default.
  • Button: A “try it” button has been created to show up the pop up box having OK and Cancel buttons upon click event.

(Click on image to view enlarged)

 

webdriver alerts 2

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 a note that for script creation, we would be using “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

webdriver alerts 3

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 have always been a little tricky as we know Selenium is an automation testing tool which supports only web application testing, that means, it doesn’t support windows based applications and window alert is one of them. However Selenium alone can’t help the situation but along with some third-party intervention, this problem can be overcome.

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 which 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 would be using “gmail.com”. I believe the application doesn’t require any more introductions.

Scenario to be automated

  1. Launch the web browser and open the application – “gmail.com”
  2. Enter 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 take a note that for script creation, we would be using “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 be used to populate the value in the window based alert with the help of keyPress and keyRelease events.

Article summary:

  • Alerts are 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.
  • 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 be able to create a WebDriver script for handling a drop-down and making the Select class accessible.
  • WebDriver offers the users with a very efficient way to handle these pop ups using 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 have always been a little tricky as we know Selenium is an automation testing tool which supports only web application testing, that means, it doesn’t support windows based applications and window alert is one of them.
  • Robot class is a java based utility which emulates the keyboard and mouse actions and can be effectively used to handling window based pop up 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 would discuss about 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 in order 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 your queries/comments about this or any other previous tutorials in comments below.

Recommended Reading

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

  1. Usefull information…..

    Reply
  2. does this method work for all types of popup windows?

    Reply
  3. @Vasim

    Thank you.

    Reply
  4. @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
  5. 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
  6. This is a great article. top information on how to work with Selenium. can I offer you publishing this article in QATestingTools.com ?

    Reply
  7. 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
  8. how to handle jquery dialog having yes no button using selenium webdriver

    Reply
  9. 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
  10. What if alert is not displayed all the time?, I mean, it may be displayed are may not be displayed, how to handle such situation?

    Reply
  11. if the pop up window does not have yes or no button it have close symbol and subscribe button then what to do

    Reply
  12. 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
  13. 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
  14. 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
    • hey dude! its just a exception you can control it. check the Xapth take an unic value run it again.

      Reply
  15. 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
  16. 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
  17. Sir this examples using java,how to check the same problems using C# in

    Reply
  18. How to handle “Location Tracker” window pop in selenium wbdriver. kindly give me suggestion

    Reply
  19. 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
  20. 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
  21. Very Good Notes. Helps a lot for many people.

    Reply
  22. 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
  23. Could u give the same code for the C# and in firefox browser???

    I think it is also browser dependent, In chrome it runs fine!!

    Reply
  24. 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
  25. 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
  26. 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
    • hey dude! first you want to check the findElement word and the run this program do it bro.

      Reply
  27. HI,i am a beginner in selenium, could you please help me with my queries, how to handle runtime pop up ?

    Reply
  28. Can I use AutoIt tool in stead of Robot Class?

    Reply
  29. Can you share the exact path where I can find the “Learning_Selenium” project

    Reply
  30. 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
  31. 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
  32. 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
  33. How can we say that it is a window based popup and it is web based popup.

    Reply
  34. 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
  35. 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
  36. 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
  37. 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
  38. Hi,
    for facebook this alert code is not working

    Reply
  39. 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
  40. 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
  41. 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
  42. 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
  43. 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
  44. 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
  45. Can we Enter text into alert boxes?
    you mentioned in summary points that we can enter data using sendKeys() method is it possible?

    Reply
  46. 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
  47. 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

Leave a Comment